Java Concurrency Interview

Live coding puzzles question 180 of 180 junior

Two threads, one increments and one prints a shared counter. What could go wrong, and how do you fix it by hand?

Two separate bugs live in this three-line program, and naming both is the test.

Visibility: with a plain field, the reader has no happens-before edge and the JIT may hoist the read out of its loop, so it can print the same value forever. Atomicity: count++ is read-modify-write, so with a second incrementer, updates are lost. With exactly one writer the second problem does not arise, which is why volatile alone is a correct fix for this program and not for the obvious next version of it.

The safe answers, in order of preference: AtomicInteger (covers both, no lock), a lock around both the increment and the read (covers both, and extends to more state), or volatile (covers visibility only, and only correct while there is exactly one writer). Saying which of these stops working when a third thread appears is the answer they want.

puzzle visibility atomicity

Quiz yourself on Live coding puzzles Suggest a correction