Skip to main content

Practice Β· 2 of 3

Watch a lost update happen (then avoid it)

Demonstrate atomicity gaps WITHOUT timing luck, using latch choreography: 1. static List<Integer> racyIncrement() — two virtual threads each await go, then read a plain int counter field, add 1, and write it back, each recording the value they wrote; main releases go once both are ready and joins both. 2. Return the two written values. With both threads interleaved read→write, at least one update is usually lost — but this test only requires the method to be *structurally* racy: implement it exactly as described (read, add, write — no synchronization). 3. static int atomicIncrement() — same scenario but using AtomicInteger.incrementAndGet(); must always return 2 when called after both threads complete.

Difficulty: advanced

Back to lesson: Practice: JMM drills