...
The use of the volatile
keyword is inappropriate for composite operations on shared variables (CON01-J. Ensure atomicity of composite operations and visibility of results).
Noncompliant Code Example
Thread-safe objects 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;
final int size = 1000;
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;
final int size = 1000;
// ...
}
|
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.
...