...
Notably, this applies only to fields and not to the contents of arrays that are declared volatile
. A thread may not observe a recent write to the array's element from another thread.
Noncompliant Code Example
This noncompliant code example shows an array that is declared volatile
. It appears that, when a value is written by a thread to one of the array elements, it will be visible to other threads immediately. This is misleading because the volatile
keyword just makes the array reference visible to all threads and does not affect the actual data contained within the array.
Code Block | ||
---|---|---|
| ||
class Unsafe { private volatile int[] arr = new int[20]; // ... } arr[2] = 10; |
Compliant Solution
This compliant solution suggests using the java.util.concurrent.atomic.AtomicIntegerArray
concurrency utility. Using its set(index, value)
method ensures that the write is atomic and the resulting value is immediately visible to other threads. The other threads can retrieve a value from a specific index by using the get(index)
method.
Code Block | ||
---|---|---|
| ||
class Safe { AtomicIntegerArray aia = new AtomicIntegerArray(5); // Other code } aia.set(1, 10); |
Risk Assessment
The assumption that the contents of an array declared volatile
, are volatile
, can lead to stale reads.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON03- J | low | probable | medium | P4 | L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[JLS 05|AA. Java References#JLS 05]\] |
...