Volatile Increment Is Not Atomic

ID

java.volatile_increment

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:362, concurrency, reliability

Description

Reports ` or `--` operations on fields declared `volatile`. Although `volatile` guarantees visibility of reads and writes across threads, increment and decrement are compound read-modify-write operations that are NOT atomic. Two threads performing `volatileField concurrently can lose updates.

Rationale

A volatile int counter; counter++; compiles to a read, an increment, and a write. The volatile keyword ensures each individual read and write is visible to all threads, but does NOT ensure that the three-step sequence executes atomically. If two threads read the same value simultaneously, both increment to the same result, and one update is lost.

// Bad -- not atomic
private volatile int counter;

public void increment() {
    counter++;  // race condition
}

Remediation

Use AtomicInteger, AtomicLong, or explicit synchronization:

// Good -- atomic operations
private final AtomicInteger counter = new AtomicInteger();

public void increment() {
    counter.incrementAndGet();
}