Name

ThreadLocal<T>

Synopsis

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 ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.