...
Noncompliant Code Example
This noncompliant code example consists of two classes, an immutable ImmutablePoint
class and a mutable Holder
class. Holder
is mutable because a new ImmutablePoint
instance can be assigned to it using the setPoint()
method. If one thread updates the value of the ipoint
field, another thread may still see the reference of the old value.
Code Block | ||
---|---|---|
| ||
class Holder {
ImmutablePoint ipoint;
Holder(ImmutablePoint ip) {
ipoint = ip;
}
void getPoint() {
return ipoint();
}
void setPoint(ImmutablePoint ip) {
this.ipoint = ip;
}
}
public class ImmutablePoint {
final int x = 20;
final int y = 10;
}
|
Compliant Solution
This compliant solution declares the ipoint
field as volatile
so that updates are immediately visible to other threads.
Code Block | ||
---|---|---|
| ||
class Holder {
volatile ImmutablePoint ipoint;
Holder(ImmutablePoint ip) {
ipoint = ip;
}
void getPoint() {
return ipoint();
}
void setPoint(ImmutablePoint ip) {
this.ipoint = ip;
}
}
|
Note that no synchronization is necessary for the setPoint()
method because it operates atomically on immutable data, that is, on an instance of ImmutablePoint
.
Declaring immutable fields as volatile
enables their safe publication, in that, once published, it is impossible to change the state of the sub-object.
Noncompliant Code Example
Thread-safe objects (which may not be strictly immutable) must declare their nonfinal fields as volatile
to ensure that no thread sees any field references before the sub-objects' initialization has concluded. This noncompliant code example does not declare the map
field as volatile
.
Code Block | ||
---|---|---|
| ||
public class Container<K,V> { Map<K,V> map; public Container() { map = new HashMap<K,V>(); // Put values in HashMap } public V get(Object k) { return map.get(k); } } |
Compliant Solution
This compliant solution declares the map
field as volatile
to ensure other threads see an up-to-date HashMap
reference and object state.
Code Block | ||
---|---|---|
| ||
public class Container<K,V> { volatile Map<K,V> map; // ... } |
...
Risk Assessment
Failing to use volatile to guarantee visibility of shared values across multiple thread and prevent reordering of statements can result in unpredictable control flow.
...