Java Reference
In-Depth Information
Note Neither the Java language nor the JVM provides a way to prevent deadlock,
andsotheburdenfallsonyou.Thesimplestwaytopreventdeadlockfromhappening
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
asynchronizedmethodinaJavaAPI,andtheadviceisoverkillbecausethesynchron-
ized method/block being called might not call any other synchronized method/block,
so deadlock would not occur.
Youwillsometimeswanttoassociateper-threaddata(suchauserID)withathread.
Althoughyoucanaccomplishthistaskwithalocalvariable,youcanonlydosowhile
the local variable exists. You could use an instance field to keep this data around
longer,butthenyouwouldhavetodealwithsynchronization.Thankfully,Javasupplies
ThreadLocal as a simple (and very handy) alternative.
Eachinstanceofthe ThreadLocal classdescribesa thread-local variable ,whichis
avariablethatprovidesaseparatestorageslottoeachthreadthataccessesthevariable.
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-
tialValue() .
void set(T value) sets the value of the calling thread's storage slot to
value .
Listing 4-29 shows you how to use ThreadLocal to associate a different user ID
with each of two threads.
Search WWH ::




Custom Search