Volatile on Array Field
ID |
java.volatile_on_array_field |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:567, concurrency, reliability |
Description
Reports fields declared volatile whose type is an array. The volatile keyword on an array field only makes the array reference volatile, not the individual array elements.
Rationale
When a field is declared volatile, the Java Memory Model guarantees that reads and writes of that field are visible across threads. However, for an array field, only the reference to the array is volatile. Reads and writes to individual array elements (arr[i] = x) are not volatile and therefore not guaranteed to be visible to other threads. This is a common concurrency mistake that leads to subtle data races.
// Bad — elements are NOT volatile, only the reference
private volatile Object[] data;
// Good — use AtomicReferenceArray for thread-safe element access
private final AtomicReferenceArray<Object> data;
// Good — use explicit synchronization
private Object[] data; // protected by synchronized blocks