Skip to main content

Practice ยท 3 of 3

Write the CAS retry loop yourself

Do NOT use AtomicInteger's incrementAndGet. Build the loop from CAS: 1. static int casIncrement(AtomicInteger n) โ€” read, add 1, compareAndSet(read, read+1); retry the whole read on failure; return the NEW value. 2. static int concurrentCasSum(AtomicInteger n, int threads) โ€” start threads virtual threads each calling casIncrement 1000 times via a latch go-signal; join all; return n.get(). 3. static String explainAba() returns exactly: "CAS compares values, not history: A->B->A passes the compare but the state changed".

Difficulty: advanced

Back to lesson: Practice: Lock & CAS drills