org.sonar.l10n.java.rules.java.S3077.html Maven / Gradle / Ivy
Why is this an issue?
Marking an array volatile
means that the array itself will always be read fresh and never thread cached, but the items in the
array will not be. Similarly, marking a mutable object field volatile
means the object reference is volatile
but
the object itself is not, and other threads may not see updates to the object state.
This can be salvaged with arrays by using the relevant AtomicArray class, such as AtomicIntegerArray
, instead. For mutable objects,
the volatile
should be removed, and some other method should be used to ensure thread-safety, such as synchronization, or ThreadLocal
storage.
Noncompliant code example
private volatile int [] vInts; // Noncompliant
private volatile MyObj myObj; // Noncompliant
Compliant solution
private AtomicIntegerArray vInts;
private MyObj myObj;
Resources
- CERT, CON50-J. - Do not assume that declaring a reference volatile guarantees safe
publication of the members of the referenced object
© 2015 - 2024 Weber Informatics LLC | Privacy Policy