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