Repaso
Español
Java CoreAdvancedJV-31

Why is this counter NOT thread-safe even though the field is volatile?

private volatile int count = 0;

void increment() {
    count++;
}

Options

  1. volatile only works on object references, not on int fields
  2. count++ is read, add, write: two threads can read the same value (Correct option)
  3. An int field cannot be shared between threads
  4. It is thread-safe, because volatile covers every operation

Answer

Because count++ is read, add, write: two threads can read the same value and one update is lost

Why

volatile guarantees that every thread sees the latest written value. But count++ is not one step: (1) read count, (2) add 1, (3) write back.

If two threads both read 5, both write 6, and one increment is lost (a race condition).

Fixes: AtomicInteger.incrementAndGet() (lock-free and atomic), or make the method synchronized, or use LongAdder for very high contention.

private final AtomicInteger count = new AtomicInteger();

void increment() {
    count.incrementAndGet();
}

Remember

volatile does not make compound operations atomic.

Key terms

Practice this question in Repaso