Skip to main content
PProfileMatch
← Path

Advanced Java · Java Concurrency: Threads, ExecutorService and CompletableFuture

0 XP
  1. 1 current stop: learning
  2. 2 upcoming
  3. 3 upcoming
  4. 4 upcoming
  5. 5 upcoming

Finish after stop 5

Stop 1 of 5 · Stadium turnstiles at rush hour

Trick to keep in mind+3 XP

One innocent line, three hidden steps: read, add, write. Make them one step.

An increment on a shared int looks atomic but is read, add one, write back. Two threads can both read the same old value and both write the same new one, so one update disappears. The fix is to make the whole read-modify-write indivisible, either with a lock or with an atomic class built for exactly that job. Marking the field visible alone does not shrink those three steps.

Read it once, then a question tests whether the trick stuck.