Note Neither the Java language nor the JVM provides a way to prevent deadlock,
is to avoid having either a synchronized method or a synchronized block call another
synchronized method/block. Although this advice prevents deadlock from happening,
it is impractical because one of your synchronized methods/blocks might need to call
ized method/block being called might not call any other synchronized method/block,
so deadlock would not occur.
the local variable exists. You could use an instance field to keep this data around
ThreadLocal as a simple (and very handy) alternative.
Eachinstanceofthe ThreadLocal classdescribesa thread-local variable ,whichis
You can think of a thread-local variable as a multi-slot variable in which each thread
can store a different value in the same variable. Each thread sees only its value and is
unaware of other threads having their own values in this variable.
ThreadLocal is generically declared as ThreadLocal<T> , where T identifies
the type of value that is stored in the variable. This class declares the following con-
structor and methods:
• ThreadLocal() creates a new thread-local variable.
• T get() returnsthevalueinthecallingthread'sstorageslot.Ifanentrydoes
not exist when the thread calls this method, get() calls initialValue() .
• T initialValue() creates the calling thread's storage slot and stores an
initial (default) value in this slot. The initial value defaults to null. You must
subclass ThreadLocal and override this protected method to provide a
more suitable initial value.
• void remove() removes the calling thread's storage slot. If this method
is followed by get() with no intervening set() , get() calls ini-
• void set(T value) sets the value of the calling thread's storage slot to
Listing 4-29 shows you how to use ThreadLocal to associate a different user ID
with each of two threads.