FileDocCategorySizeDatePackage
ThreadLocal.javaAPI DocJava SE 5 API24721Fri Aug 26 14:57:04 BST 2005java.lang

ThreadLocal

public class ThreadLocal extends Object
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

For example, in the class below, the private static ThreadLocal instance (serialNum) maintains a "serial number" for each thread that invokes the class's static SerialNum.get() method, which returns the current thread's serial number. (A thread's serial number is assigned the first time it invokes SerialNum.get(), and remains unchanged on subsequent calls.)

public class SerialNum {
// The next serial number to be assigned
private static int nextSerialNum = 0;

private static ThreadLocal serialNum = new ThreadLocal() {
protected synchronized Object initialValue() {
return new Integer(nextSerialNum++);
}
};

public static int get() {
return ((Integer) (serialNum.get())).intValue();
}
}

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

author
Josh Bloch and Doug Lea
version
1.33, 02/19/04
since
1.2

Fields Summary
private final int
threadLocalHashCode
ThreadLocals rely on per-thread hash maps attached to each thread (Thread.threadLocals and inheritableThreadLocals). The ThreadLocal objects act as keys, searched via threadLocalHashCode. This is a custom hash code (useful only within ThreadLocalMaps) that eliminates collisions in the common case where consecutively constructed ThreadLocals are used by the same threads, while remaining well-behaved in less common cases.
private static int
nextHashCode
The next hash code to be given out. Accessed only by like-named method.
private static final int
HASH_INCREMENT
The difference between successively generated hash codes - turns implicit sequential thread-local IDs into near-optimally spread multiplicative hash values for power-of-two-sized tables.
Constructors Summary
public ThreadLocal()
Creates a thread local variable.

    
Methods Summary
TchildValue(T parentValue)
Method childValue is visibly defined in subclass InheritableThreadLocal, but is internally defined here for the sake of providing createInheritedMap factory method without needing to subclass the map class in InheritableThreadLocal. This technique is preferable to the alternative of embedding instanceof tests in methods.

        throw new UnsupportedOperationException();
    
static java.lang.ThreadLocal$ThreadLocalMapcreateInheritedMap(java.lang.ThreadLocal$ThreadLocalMap parentMap)
Factory method to create map of inherited thread locals. Designed to be called only from Thread constructor.

param
parentMap the map associated with parent thread
return
a map containing the parent's inheritable bindings

        return new ThreadLocalMap(parentMap);
    
voidcreateMap(java.lang.Thread t, T firstValue)
Create the map associated with a ThreadLocal. Overridden in InheritableThreadLocal.

param
t the current thread
param
firstValue value for the initial entry of the map
param
map the map to store.

        t.threadLocals = new ThreadLocalMap(this, firstValue);
    
public Tget()
Returns the value in the current thread's copy of this thread-local variable. Creates and initializes the copy if this is the first time the thread has called this method.

return
the current thread's value of this thread-local

        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            return (T)map.get(this);

        // Maps are constructed lazily.  if the map for this thread
        // doesn't exist, create it, with this ThreadLocal and its
        // initial value as its only entry.
        T value = initialValue();
        createMap(t, value);
        return value;
    
java.lang.ThreadLocal$ThreadLocalMapgetMap(java.lang.Thread t)
Get the map associated with a ThreadLocal. Overridden in InheritableThreadLocal.

param
t the current thread
return
the map

        return t.threadLocals;
    
protected TinitialValue()
Returns the current thread's initial value for this thread-local variable. This method will be invoked at most once per accessing thread for each thread-local, the first time the thread accesses the variable with the {@link #get} method. The initialValue method will not be invoked in a thread if the thread invokes the {@link #set} method prior to the get method.

This implementation simply returns null; if the programmer desires thread-local variables to be initialized to some value other than null, ThreadLocal must be subclassed, and this method overridden. Typically, an anonymous inner class will be used. Typical implementations of initialValue will invoke an appropriate constructor and return the newly constructed object.

return
the initial value for this thread-local

        return null;
    
private static synchronized intnextHashCode()
Compute the next hash code. The static synchronization used here should not be a performance bottleneck. When ThreadLocals are generated in different threads at a fast enough rate to regularly contend on this lock, memory contention is by far a more serious problem than lock contention.


                                                       
         
        int h = nextHashCode;
        nextHashCode = h + HASH_INCREMENT;
        return h;
    
public voidremove()
Removes the value for this ThreadLocal. This may help reduce the storage requirements of ThreadLocals. If this ThreadLocal is accessed again, it will by default have its initialValue.

since
1.5

         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     
public voidset(T value)
Sets the current thread's copy of this thread-local variable to the specified value. Many applications will have no need for this functionality, relying solely on the {@link #initialValue} method to set the values of thread-locals.

param
value the value to be stored in the current threads' copy of this thread-local.

        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);