Java Reference
In-Depth Information
Immutable objects can be used safely by any thread without additional synchronization, even
when synchronization is not used to publish them.
This guarantee extends to the values of all final fields of properly constructed objects; final
fields can be safely accessed without additional synchronization. However, if final fields refer
to mutable objects, synchronization is still required to access the state of the objects they refer
to.
3.5.3. Safe Publication Idioms
Objects that are not immutable must be safely published , which usually entails synchroniza-
tion by both the publishing and the consuming thread. For the moment, let's focus on ensuring
that the consuming thread can see the object in its aspublished state; we'll deal with visibility
of modifications made after publication soon.
To publish an object safely, both the reference to the object and the object's state must be
made visible to other threads at the same time. A properly constructed object can be safely
published by:
Initializing an object reference from a static initializer;
Storing a reference to it into a volatile field or AtomicReference ;
Storing a reference to it into a final field of a properly constructed object; or
Storing a reference to it into a field that is properly guarded by a lock.
The internal synchronization in thread-safe collections means that placing an object in a
thread-safe collection, such as a Vector or synchronizedList , fulfills the last of these
requirements. If thread A places object X in a thread-safe collection and thread B subse-
quently retrieves it, B is guaranteed to see the state of X as A left it, even though the applic-
ation code that hands X off in this manner has no explicit synchronization. The thread-safe
library collections offer the following safe publication guarantees, even if the Javadoc is less
than clear on the subject:
Placing a key or value in a Hashtable , synchronizedMap , or Concurrent-
Map safely publishes it to any thread that retrieves it from the Map (whether directly
or via an iterator);
Placing an element in a Vector , CopyOnWriteArrayList , CopyOnWrite-
ArraySet , synchronizedList , or synchronizedSet safely publishes it to
any thread that retrieves it from the collection;
Search WWH ::




Custom Search