According to the Java Language Specification [JLS 2011], §8.3.1.4, "volatile
Fields,",
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 noncompliant code example declares a volatile reference to an array object.:
Code Block | ||
---|---|---|
| ||
final class Foo { private volatile int[] arr = new int[20]; public int getFirst() { return arr[0]; } public void setFirst(int n) { arr[0] = n; } // ... } |
...
The root of the problem is that the thread that calls setFirst()
and the thread that calls getFirst()
lack a happens-before relationship. A happens-before relationship exists between a thread that writes to a volatile variable and a thread that subsequently reads it. However, setFirst()
and getFirst()
only read from a volatile variable—the volatile reference to the array; neither method writes to the volatile variable.
...
To ensure that the writes to array elements are atomic and that the resulting values are visible to other threads, this compliant solution uses the AtomicIntegerArray
class defined in java.util.concurrent.atomic
.:
Code Block | ||
---|---|---|
| ||
final class Foo { private final AtomicIntegerArray atomicArray = new AtomicIntegerArray(20); public int getFirst() { return atomicArray.get(0); } public void setFirst(int n) { atomicArray.set(0, 10); } // ... } |
...
This noncompliant code example declares the Map instance Map
instance field volatile. The instance of the Map
object can be mutated using the put()
method; consequently, it is a mutable object.
...
Interleaved calls to get()
and put()
may result in internally inconsistent values being retrieved from the Map object Map
object because the operations within put()
modify its state. Declaring the object reference volatile is insufficient to eliminate this data race.
...
The volatile-read, synchronized-write technique uses synchronization to preserve atomicity of compound operations, such as increment, and provides faster access times for atomic reads. However, it fails for mutable objects because the safe publication guarantee provided by volatile
extends only to the field itself (the primitive value or object reference); the referent (and hence the referent's members) is excluded from the guarantee. Consequently, the write and a subsequent read of the map
lack a happens-before relationship.
...
This compliant solution uses method synchronization to guarantee visibility.:
Code Block | ||
---|---|---|
| ||
final class Foo { private final Map<String, String> map; public Foo() { map = new HashMap<String, String>(); // Load some useful values into map } public synchronized String get(String s) { return map.get(s); } public synchronized void put(String key, String value) { // Validate the values before inserting if (!value.matches("[\\w]*")) { throw new IllegalArgumentException(); } map.put(key, value); } } |
It is unnecessary to declare the map field map
field volatile because the accessor methods are synchronized. The field is declared final
to prevent publication of its reference when the referent is in a partially initialized state (see rule TSM03-J. Do not publish partially initialized objects for more information).
...
In this noncompliant code example, the volatile format
field stores a reference to a mutable object, java.text.DateFormat
.:
Code Block | ||
---|---|---|
| ||
final class DateHandler { private static volatile DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM); public static java.util.Date parse(String str) throws ParseException { return format.parse(str); } } |
Because DateFormat
is not thread-safe [API 2011] Class DateFormat, the value for Date
returned by the parse()
method might fail to correspond to the str
argument.
...
This compliant solution creates and returns a new DateFormat
instance for each invocation of the parse()
method [API 2011] Class DateFormat.:
Code Block | ||
---|---|---|
| ||
final class DateHandler { public static java.util.Date parse(String str) throws ParseException { return DateFormat.getDateInstance(DateFormat.MEDIUM).parse(str); } } |
This solution complies with rule OBJ05-J. Defensively copy private mutable class members before returning their references because the class no longer contains internal mutable state.
...
This compliant solution makes DateHandler
thread-safe by synchronizing statements within the parse()
method [API 2011] Class DateFormat.:
Code Block | ||
---|---|---|
| ||
final class DateHandler { private static DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM); public static java.util.Date parse(String str) throws ParseException { synchronized (format) { return format.parse(str); } } } |
...
This compliant solution uses a ThreadLocal
object to create a separate DateFormat
instance per thread.:
Code Block | ||
---|---|---|
| ||
final class DateHandler { private static final ThreadLocal<DateFormat> format = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return DateFormat.getDateInstance(DateFormat.MEDIUM); } }; // ... } |
...
[API 2011] | |
Pattern #2: 2, "One-time safe publicationTime Safe Publication" | |
[JLS 2011] | |
"Mutable Statics" |
...