Details
-
Type:
Bug Detection
-
Status: Active
-
Resolution: Unresolved
-
Labels:
-
Message:Mark this "xxx" "volatile" or use an "AtomicXxx" instead.
-
Highlighting:
-
Default Severity:Major
-
Impact:Low
-
Likelihood:High
-
Targeted languages:Java
-
Remediation Function:Constant/Issue
-
Constant Cost:10min
-
CERT:VNA00-J., VNA05-J.
Description
Primitives can be read and written to atomically. Except for long and double, that is. These 64-bit primitives must be marked volatile in multi-threaded environments, or swapped out for their atomic counterparts: AtomicLong, and AtomicDouble to guarantee that their updates are always visible to other threads.
Similarly, to ensure that updates to 32-bit primitives are visible to all threads, they should also be marked volatile.
Noncompliant Code Example
long m = 0; // Noncompliant public void increment() { m++; }
Compliant Solution
volatile long m = 0; public void increment() { m++; }
or
AtomicLong m = new AtomicLong(0); public void increment() { m.incrementAndGet(); }
See
- CERT, VNA00-J. - Ensure visibility when accessing shared primitive variables
- CERT, VNA05-J. - Ensure atomicity when reading and writing 64-bit values
Attachments
Issue Links
- relates to
-
RSPEC-3687 Atomic types should be used instead of "volatile" types
- Active