Java Reference
In-Depth Information
Because synchronization was not used to make the Holder visible to other threads, we say
the Holder was not properly published . Two things can go wrong with improperly pub-
lished objects. Other threads could see a stale value for the holder field, and thus see a
null reference or other older value even though a value has been placed in holder . But far
worse, other threads could see an up-todate value for the holder reference, but stale values
for the state of the Holder . [16] To make things even less predictable, a thread may see a
stale value the first time it reads a field and then a more up-to-date value the next time, which
is why assertSanity can throw AssertionError .
At the risk of repeating ourselves, some very strange things can happen when data is shared
across threads without sufficient synchronization.
3.5.2. Immutable Objects and Initialization Safety
Because immutable objects are so important, the JavaMemory Model offers a special guaran-
tee of initialization safety for sharing immutable objects. As we've seen, that an object refer-
ence becomes visible to another thread does not necessarily mean that the state of that object
is visible to the consuming thread. In order to guarantee a consistent view of the object's state,
synchronization is needed.
Immutable objects, on the other hand, can be safely accessed even when synchronization is
not used to publish the object reference . For this guarantee of initialization safety to hold,
all of the requirements for immutability must be met: unmodi-fiable state, all fields are fi-
nal , and proper construction. (If Holder in Listing 3.15 were immutable, assertSan-
ity could not throw AssertionError , even if the Holder was not properly published.)
Search WWH ::




Custom Search