This
class provides a convenient way to create thread-local
variables.
When you declare a static field in a class, there is only one value
for that field, shared by all objects of the class. When you declare
a nonstatic instance field in a class, every object of the class has
its own separate copy of that variable.
ThreadLocal provides an option between these two
extremes. If you declare a static field to hold a
THReadLocal object, that
ThreadLocal holds a different value for each
thread. Objects running in the same thread see the same value when
they call the get( ) method of the
ThreadLocal object. Objects running in different
threads obtain different values from get( ),
however.
In Java 5.0, this class has been made
generic and the type variable T represents
the type of the object referenced by this
ThreadLocal.
The set( ) method
sets the value held by the THReadLocal object for
the currently running thread. get( ) returns the
value held for the currently running thread. Note that there is no
way to obtain the value of the ThreadLocal object
for any thread other than the one that calls get(
). To understand the ThreadLocal class,
you may find it helpful to think of a ThreadLocal
object as a hashtable or java.util.Map that maps
from Thread objects to arbitrary values. Calling
set( ) creates an association between the current
Thread (Thread.currentThread(
)) and the specified value. Calling get(
) first looks up the current thread, then uses the
hashtable to look up the value associated with that current thread.
If a thread calls get( ) for the first time
without having first called set( ) to establish a
thread-local value, get( ) calls the protected
initialValue( ) method to obtain the initial
value to return. The default implementation of initialValue(
) simply returns null, but subclasses
can override this if they desire.
See also InheritableThreadLocal, which allows
thread-local values to be inherited from parent threads by child
threads.
public class ThreadLocal<T> {
// Public Constructors
public ThreadLocal( );
// Public Instance Methods
public T get( );
5.0 public void remove( );
public void set(T value);
// Protected Instance Methods
protected T initialValue( ); constant
}