Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Confusing a volatile object with the volatility of its member objects is a similar error to the one described in guideline OBJ50-JG. Never confuse the immutability of a reference with that of the referenced object.

Noncompliant Code Example (Arrays)

This noncompliant code example declares a volatile reference to an array object.

...

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() read only from a volatile variable—the volatile reference to the array; neither method writes to the volatile variable.

Compliant Solution (AtomicIntegerArray)

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.

...

AtomicIntegerArray guarantees a happens-before relationship between a thread that calls atomicArray.set() and a thread that subsequently calls atomicArray.get().

Compliant Solution (Synchronization)

To ensure visibility, accessor methods may synchronize access while performing operations on nonvolatile elements of an array, whether the array is referred to by a volatile or a nonvolatile reference. Note that the code is thread-safe even though the array reference is not volatile.

...

Synchronization establishes a happens-before relationship between threads that synchronize on the same lock. In this case, the thread that calls setFirst() and the thread that subsequently calls getFirst() both synchronize on the Foo instance, so safe publication is guaranteed.

Noncompliant Code Example (Mutable Object)

This noncompliant code example declares the Map instance field volatile. The instance of the Map object is mutable because of its put() method.

...

Interleaved calls to get() and put() may result in internally inconsistent values being retrieved from the Map object because the operations within put() modify its state. Declaring the object reference volatile is insufficient to eliminate this data race.

Noncompliant Code Example (Volatile-Read, Synchronized-Write)

This noncompliant code example attempts to use the volatile-read, synchronized-write technique described in "Java Theory and Practice" [Goetz 2007]. The map field is declared volatile to synchronize its reads and writes. The put() method is also synchronized to ensure that its statements are executed atomically.

...

This technique is also discussed in VNA02-J. Ensure that compound operations on shared variables are atomic.

Compliant Solution (Synchronized)

This compliant solution uses method synchronization to guarantee visibility:

...

It is unnecessary to declare the 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 TSM03-J. Do not publish partially initialized objects for more information).

Noncompliant Code Example (Mutable Subobject)

In this noncompliant code example, the volatile format field stores a reference to a mutable object, java.text.DateFormat:

...

Because DateFormat is not thread-safe [API 2011], the value for Date returned by the parse() method might fail to correspond to the str argument:

Compliant Solution (Instance per Call/Defensive Copying)

This compliant solution creates and returns a new DateFormat instance for each invocation of the parse() method [API 2011]:

...

This solution complies with OBJ05-J. Defensively copy private mutable class members before returning their references because the class no longer contains internal mutable state.

Compliant Solution (Synchronization)

This compliant solution makes DateHandler thread-safe by synchronizing statements within the parse() method [API 2011]:

Code Block
bgColor#ccccff
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);
    }
  }
}

Compliant Solution (ThreadLocal Storage)

This compliant solution uses a ThreadLocal object to create a separate DateFormat instance per thread:

Code Block
bgColor#ccccff
final class DateHandler {
  private static final ThreadLocal<DateFormat> format = new ThreadLocal<DateFormat>() {
    @Override protected DateFormat initialValue() {
      return DateFormat.getDateInstance(DateFormat.MEDIUM);
    }
  };
  // ...
}

Applicability

Incorrectly assuming that declaring a field volatile guarantees safe publication of a referenced object's members can cause threads to observe stale or inconsistent values.

Technically, strict immutability of the referent is a stronger condition than is fundamentally required for safe publication. When it can be determined that a referent is thread-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 2011]

Class DateFormat

[Goetz 2007]

Pattern 2, "One-Time Safe Publication"

[JLS 2011]

§8.3.1.4, "volatile Fields"

[Miller 2009]

"Mutable Statics"

...