You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 10 Next »

According to the Java Language Specification [[JLS 05]], section, 8.3.1.4 volatile Fields:

A field may be declared volatile, in which case the Java memory model (§17) ensures that all threads see a consistent value for the variable.

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.

class Unsafe {
  private volatile int[] arr = new int[20];
  // other code
}
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.

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

[[JLS 05]]


CON02-J. Facilitate thread reuse by using Thread Pools      11. Concurrency (CON)      CON30-J. Synchronize access to shared mutable variables

  • No labels