Java Reference
In-Depth Information
get
and
set
accessormethods that maintain a separate copy of the value for each thread that
uses it, so a
get
returns the most recent value passed to
set
from the currently executing
thread
.
Thread-local variables are often used to prevent sharing in designs based on mutable
Singletons or global variables. For example, a single-threaded application might maintain a
global database connection that is initialized at startup to avoid having to pass a
Connec-
tion
to every method. Since JDBC connections may not be thread-safe, a multithreaded
application that uses a global connection without additional coordination is not thread-
safe either. By using a
ThreadLocal
to store the JDBC connection, as in
Connec-
tionHolder
in
Listing 3.10
, each thread will have its own connection.
Listing 3.10. Using
ThreadLocal
to Ensure thread Confinement.
This technique can also be used when a frequently used operation requires a temporary object
such as a buffer and wants to avoid reallocating the temporary object on each invocation.
For example, before Java 5.0,
Integer.toString
used a
ThreadLocal
to store the
12-byte buffer used for formatting its result, rather than using a shared static buffer (which
would require locking) or allocating a new buffer for each invocation.
[11]
When a thread calls
ThreadLocal.get
for the first time,
initialValue
is consulted
to provide the initial value for that thread. Conceptually, you can think of a
ThreadLocal<T>
as holding a
Map<Thread,T>
that stores the thread-specific values,
though this is not how it is actually implemented. The thread-specific values are stored in the