Java Reference
In-Depth Information
Chapter 5. Programmer Misconceptions
The guidelines in this chapter address areas where developers often make unwarranted as-
sumptions about Java language and library behaviors, or where ambiguities can easily be
introduced. Failure to follow these guidelines can result in programs that produce counter-
intuitive results.
This chapter contains guidelines that address
1. Misconceptions about Java APIs and language features
2. Assumptions and ambiguity-laced programs
3. Situations in which the programmer wanted to do one thing but ended up doing an-
other
66. Do not assume that declaring a reference volatile guarantees safe
publication of the members of the referenced object
According to the Java Language Specification (JLS), §8.3.1.4, “ volatile Fields” [JLS
2013],
A field may be declared volatile , in which case the Java Memory Model ensures
that all threads see a consistent value for the variable (§17.4).
This safe publication guarantee applies only to primitive fields and object references.
Programmers commonly use imprecise terminology and speak about “member objects.”
For the purposes of this visibility guarantee, the actual member is the object reference; the
objectsreferredto(aka, referents )byvolatileobjectreferencesarebeyondthescopeofthis
safe publication guarantee. Consequently, declaring an object reference to be volatile is in-
sufficient to guarantee that changes to the members of the referent are published to other
threads. A thread may fail to observe a recent write from another thread to a member field
of such an object referent.
Furthermore, when the referent is mutable and lacks thread-safety, other threads might
see a partially constructed object or an object in a (temporarily) inconsistent state [Goetz
2007]. However, when the referent is immutable, declaring the reference volatile suffices
to guarantee safe publication of the members of the referent. Programmers cannot use the
volatile keyword to guarantee safe publication of mutable objects. Use of the volatile
keywordcanonlyguaranteesafepublicationofprimitivefields,objectreferences,orfields
of immutable object referents.
Search WWH ::




Custom Search