This class gives thread-local variables. These variables differ from their traditional matches in that each thread that accesses one (via its get or set method) has its own, individually initialized copy of the variable. ThreadLocal cases are typically private static fields in classes that require to associate the state with a thread (e.g., a user ID or Transaction ID).
For example, the class below creates unique identifiers local to each thread. A thread's id is indicated the first time it invokes ThreadId.get() and remains stable on subsequent calls.
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadId {
private static final AtomicInteger nextId = new AtomicInteger(0);
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
};
public static int get() {
return threadId.get();
}
}
Each thread operates an implicit reference to its image of a thread-local variable as long as the thread is running and the ThreadLocal instance is available; after a thread goes away, all of its copies of thread-local cases are subject to garbage collection (except other references to these copies exist).