Java Reference
In-Depth Information
Thread object itself; when the thread terminates, the thread-specific values can be garbage
collected.
If you are porting a single-threaded application to a multithreaded environment, you can pre-
serve thread safety by converting shared global variables into ThreadLocal s, if the se-
mantics of the shared globals permits this; an applicationwide cache would not be as useful
if it were turned into a number of thread-local caches.
ThreadLocal is widely used in implementing application frameworks. For example, J2EE
containers associate a transaction context with an executing thread for the duration of an
EJB call. This is easily implemented using a static Thread-Local holding the transaction
context: when framework code needs to determine what transaction is currently running, it
fetches the transaction context from this ThreadLocal . This is convenient in that it reduces
the need to pass execution context information into every method, but couples any code that
uses this mechanism to the framework.
It is easy to abuse ThreadLocal by treating its thread confinement property as a license
to use global variables or as a means of creating “hidden” method arguments. Like global
variables, thread-local variables can detract from reusability and introduce hidden couplings
among classes, and should therefore be used with care.
3.4. Immutability
The other end-run around the need to synchronize is to use immutable objects [EJ Item 13].
Nearly all the atomicity and visibility hazards we've described so far, such as seeing stale val-
ues, losing updates, or observing an object to be in an inconsistent state, have to do with the
vagaries of multiple threads trying to access the same mutable state at the same time. If an
object's state cannot be modified, these risks and complexities simply go away.
An immutable object is one whose state cannot be changed after construction. Immutable ob-
jects are inherently thread-safe; their invariants are established by the constructor, and if their
state cannot be changed, these invariants always hold.
Immutable objects are always thread-safe.
Immutable objects are simple . They can only be in one state, which is carefully controlled by
the constructor. One of the most difficult elements of program design is reasoning about the
Search WWH ::




Custom Search