Java Reference
In-Depth Information
In the d method, the compiler is allowed to reorder the reads of x and the call to g
freely. Thus, new A().f() could return -1 , 0 , or 1 .
An implementation may provide a way to execute a block of code in a final -field-safe con-
text . If an object is constructed within a final -field-safe context, the reads of a final field of
that object will not be reordered with modifications of that final field that occur within that
final -field-safe context.
A final -field-safe context has additional protections. If a thread has seen an incorrectly pub-
lished reference to an object that allows the thread to see the default value of a final field,
and then, within a final -field-safe context, reads a properly published reference to the ob-
ject, it will be guaranteed to see the correct value of the final field. In the formalism, code
executed within a final -field-safe context is treated as a separate thread (for the purposes of
final field semantics only).
In an implementation, a compiler should not move an access to a final field into or out of
a final -field-safe context (although it can be moved around the execution of such a context,
so long as the object is not constructed within that context).
One place where use of a final -field-safe context would be appropriate is in an executor
or thread pool. By executing each Runnable in a separate final -field-safe context, the
executor could guarantee that incorrect access by one Runnable to a object o will not
remove final field guarantees for other Runnable s handled by the same executor.
17.5.4. Write-protected Fields
Normally, a field that is final and static may not be modified. However, System.in , System.out ,
and System.err are static final fields that, for legacy reasons, must be allowed to be changed
by the methods System.setIn , System.setOut , and System.setErr . We refer to these fields as being
write-protected to distinguish them from ordinary final fields.
The compiler needs to treat these fields differently from other final fields. For example, a
read of an ordinary final field is “immune” to synchronization: the barrier involved in a lock
or volatile read does not have to affect what value is read from a final field. Since the value
of write-protected fields may be seen to change, synchronization events should have an ef-
fect on them. Therefore, the semantics dictate that these fields be treated as normal fields
that cannot be changed by user code, unless that user code is in the System class.
17.6. Word Tearing
One consideration for implementations of the Java Virtual Machine is that every field and
array element is considered distinct; updates to one field or element must not interact with
Search WWH ::




Custom Search