Video in progress
Why does this counter give a wrong result even though it is volatile?
class Hits {
private volatile int count;
void hit() { count++; }
int get() { return count; }
}
// 10 threads x 10_000 calls of hit() -> get() = ?
volatile guarantees only visibility, while count++ is three separate operations: read, add, write. Two threads read the same old value and overwrite each other.
📖 Answer
The expected result is 100,000, but in practice a different, smaller number comes out on every run.
volatile guarantees this: every thread reads the most recently written value of count. But nothing prevents another thread from getting in between the read and the write:
T1: read 41
T2: read 41
T1: wrote 42
T2: wrote 42 // one increment was lost
Ways to fix it:
private final AtomicInteger count = new AtomicInteger();
void hit() { count.incrementAndGet(); }
or, if very many threads increment at once, LongAdder, or synchronized void hit().
After this question, interviewers often ask "so when is volatile enough?". The answer: when the write doesn't depend on the value that was read, for example running = false or swapping in a ready configuration object.
Sign up to mark studied questions and save your progress.