In order to make up the word, the Oracle document introduced threadlocal copied over
Threadlocal<t>extends Object
This class provides thread-local variables. These variables differ from their normal counterparts in so each thread this accesses one (via itsGetOrSetmethod) has its own, independently initialized copy of the variable.ThreadLocalInstances is typically private static fields in classes this wish to associate state with a thread (e.g., a user ID or Tr Ansaction ID).
For example, the class below generates a unique identifiers local to each thread. A thread ' s ID is assigned the first time it invokes Threadid.get () and remains unchanged on subsequent calls.
Import Java.util.concurrent.atomic.AtomicInteger; public class ThreadId { //Atomic integer containing the next thread ID to be assigned private static final Atomic Integer NextID = new Atomicinteger (0); Thread local variable containing each thread ' s ID private static final threadlocal<integer> threadId = NE W threadlocal<integer> () { @Override protected Integer initialvalue () { return nextid.getandincrement () ; } }; Returns the current thread's unique ID, assigning it if necessary public static int get () { return THREADID.G ET ();
Each thread holds an implicit reference to their 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 is subject to garbage collection (unless other Refe Rences to these copies exist).
Java Multithreaded Learning-threadlocal