Java Reference
In-Depth Information
case. The problem is that, while the shared object is immutable, the ref-
erence used to access the shared object is itself shared and often mut-
ableconsequently, a correctly synchronized program must synchronize
access to that shared reference, but often programs do not do this, be-
cause programmers do not recognize the need to do it. For example,
suppose one thread creates a String object and stores a reference to it
in a static field. A second thread then uses that reference to access the
string. There is no guarantee, based on what we've discussed so far,
that the values written by the first thread when constructing the string
will be seen by the second thread when it accesses the string.
The memory model defines the semantics for multithreaded programs
and tells you what you need to do to correctly synchronize your pro-
grams. But additionally, you need safeguards that ensure that incor-
rectly synchronized programs cannot violate the integrity of the lan-
guage, or the virtual machine implementation, or the security architec-
ture that prevents sensitive API s from being misusedsee " Security " on
page 677 . These safeguards come in the form of additional rules in the
memory model covering the use of final fields.
The first rule for final fields covers the situation we described with the
shared string. Basically, the rule states that if a reference to an object
is stored after the object has been constructed, then any thread that
reads that reference is guaranteed to see initialized values for the ob-
ject's final fields. Note that there is no guarantee concerning non-final
fields of the object that are read without synchronization.
The second rule expands on the first to apply transitively to objects
reachable via final fields. There is little point being guaranteed to see a
reference stored in a final field, if the fields of that object are not guar-
anteed to be seen. What the second rule states, in general terms, is that
if you read a reference from a final field, then any non-final fields in the
referenced object will have a value at least as recent as the value they
had when the reference was written. For example, this means that if
one thread constructs an object and uses methods on that object to set
its state, then a second thread will see the state set by the first thread
if the reference used to access the object was written to a final field
after the state changes were made. Any final fields in such objects are
covered by the first rule.
 
Search WWH ::




Custom Search