Java Reference
In-Depth Information
Applicability
Incorrectly assuming that declaring a field volatile guarantees safe publication of a refer-
enced object's members can cause threads to observe stale or inconsistent values.
Technically, strict immutability of the referent is a stronger condition than is funda-
mentallyrequiredforsafepublication.Whenitcanbedeterminedthatareferentisthread-
safe by design, the field that holds its reference may be declared volatile. However, this
approach to using volatile decreases maintainability and should be avoided.
Bibliography
[API 2013]
Class DateFormat
[Goetz 2007]
Pattern 2, “One-Time Safe Publication”
[JLS 2013]
§8.3.1.4, “ volatile Fields”
[Long 2012]
OBJ05-J. Defensively copy private mutable class members before returning
their references
TSM03-J. Do not publish partially initialized objects
VNA02-J. Ensure that compound operations on shared variables are atomic
[Miller 2009]
“Mutable Statics”
67. Do not assume that the sleep() , yield() , or getState()
methods provide synchronization semantics
According to the JLS, §17.3, “Sleep and Yield” [JLS 2013],
It is important to note that neither Thread.sleep nor Thread.yield have any syn-
chronization semantics. In particular, the compiler does not have to flush writes
cached in registers out to shared memory before a call to Thread.sleep or
Thread.yield , nor does the compiler have to reload values cached in registers after
a call to Thread.sleep or Thread.yield .
Code that bases its concurrency safety on thread suspension or yields to processes that
 
Search WWH ::




Custom Search