FileDocCategorySizeDatePackage
ThreadLocal.javaAPI DocJava SE 6 API23872Tue Jun 10 00:25:38 BST 2008java.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, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes UniqueThreadIdGenerator.getCurrentThreadId() and remains unchanged on subsequent calls.

import java.util.concurrent.atomic.AtomicInteger;

public class UniqueThreadIdGenerator {

private static final AtomicInteger uniqueId = new AtomicInteger(0);

private static final ThreadLocal < Integer > uniqueNum =
new ThreadLocal < Integer > () {
@Override protected Integer initialValue() {
return uniqueId.getAndIncrement();
}
};

public static int getCurrentThreadId() {
return uniqueId.get();
}
} // UniqueThreadIdGenerator

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.42, 06/23/06
since
1.2

Fields Summary
private final int
threadLocalHashCode
ThreadLocals rely on per-thread linear-probe 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 AtomicInteger
nextHashCode
The next hash code to be given out. Updated atomically. Starts at zero.
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. If the variable has no value for the current thread, it is first initialized to the value returned by an invocation of the {@link #initialValue} method.

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

        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    
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 the first time a thread accesses the variable with the {@link #get} method, unless the thread previously invoked the {@link #set} method, in which case the initialValue method will not be invoked for the thread. Normally, this method is invoked at most once per thread, but it may be invoked again in case of subsequent invocations of {@link #remove} followed by {@link #get}.

This implementation simply returns null; if the programmer desires thread-local variables to have an initial value other than null, ThreadLocal must be subclassed, and this method overridden. Typically, an anonymous inner class will be used.

return
the initial value for this thread-local

        return null;
    
private static intnextHashCode()
Returns the next hash code.


              
        
	return nextHashCode.getAndAdd(HASH_INCREMENT); 
    
public voidremove()
Removes the current thread's value for this thread-local variable. If this thread-local variable is subsequently {@linkplain #get read} by the current thread, its value will be reinitialized by invoking its {@link #initialValue} method, unless its value is {@linkplain #set set} by the current thread in the interim. This may result in multiple invocations of the initialValue method in the current thread.

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. Most subclasses will have no need to override this method, relying solely on the {@link #initialValue} method to set the values of thread-locals.

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

        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    
private TsetInitialValue()
Variant of set() to establish initialValue. Used instead of set() in case user has overridden the set() method.

return
the initial value

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