Why is this counter NOT thread-safe even though the field is volatile?
private volatile int count = 0;
void increment() {
count++;
}Options
volatileonly works on object references, not onintfieldscount++is read, add, write: two threads can read the same value (Correct option)- An
intfield cannot be shared between threads - It is thread-safe, because
volatilecovers 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.