These activities accompany the chapter C20A. Programs use only stable JDK 25 APIs. Every answer must declare the invariant or property to guarantee before choosing a class: a lucky output does not replace explanation.
C20A-A01 — Two Requests, One Copy
Problem. In the reservation program, imagine A and B both read 1. Write the possible results of both compareAndSet(1, 0) calls and the final value. Repeat the reasoning if B arrives only after A's successful CAS. Then compile and run the program several times. Do not try to predict which reader will obtain the copy.
Acceptance criterion. The answer must show that at most one CAS can return true for that transition, that failure leaves the value unchanged and that the failed caller rereads before deciding. The complete program's output is five accepted reservations and zero available copies.
Hint. Find the exact point at which state changes from 1 to 0. The preceding read is not yet a reservation.
Reasoned solution. If both observe 1, the first CAS that actually replaces 1 with 0 returns true. The other finds 0 and returns false; on the next iteration it reads 0 and the method answers false. If B arrives after A's success, it directly reads 0 and does not call CAS. In neither order does the number become negative. The external count of true answers checks the test outcome, rather than deciding the reservation.
C20A-P01 — A Name Is Not Enough to Guarantee Order
Problem. Modify a copy of AtomicReservations so that reserve() returns a number from 1 to 5 for accepted requests and 0 for rejected ones. The number must indicate the position obtained among the five copies: when a CAS replaces observed with observed - 1, the position is 6 - observed. Collect numbers obtained by twenty workers and verify, after the join calls, that the set is exactly {1, 2, 3, 4, 5}. Explain why this position is not a persistent identifier.
Acceptance criterion. No accepted number repeats; no value outside the range 1–5 appears; fifteen requests receive 0. The answer distinguishes this in-memory numbering from a key that must remain unique after a restart or across several processes.
Hint. Return the position only in the branch where CAS succeeds. A number calculated earlier can become outdated.
Reasoned solution. In the if (compareAndSet(...)) branch, return 6 - observed; when observed is 5, 4, 3, 2, 1, the produced numbers are respectively 1, 2, 3, 4, 5. A failed CAS assigns no position and restarts. Concurrent collection can use a thread-safe queue or an array with an atomically obtained index, but verification happens after the join calls. A new process would restart from five initial copies: the persistent archive must define another guarantee for durable identity.
C20A-E01 — The Effect That Can Repeat
Problem. In the update program, someone proposes this lambda: value -> { sendEmail(); return Math.min(10, value + 2); }. Explain why it is incorrect even if the final value remains within ten. Describe a solution where confirmation is sent after the decision, indicating which failure remains possible between update and sending.
Acceptance criterion. The answer identifies possible function recalculation, duplicated sending and the new problem “state changed, email not sent”. It must not claim that merely moving the call after updateAndGet guarantees a transaction between memory and the mail service.
Hint. A function passed to an atomic update calculates a candidate; it does not necessarily represent one execution of the whole request.
Reasoned solution. If another thread updates the value before the attempt finishes, the function can be invoked again. The email from the first invocation cannot be withdrawn by the failed CAS. Sending after a successful update avoids sending for every failed attempt, but a window remains in which the program can stop before sending. Reliable confirmation requires an application protocol recording decision and message to send in the same persistent system, or an equivalent mechanism with recovery and deduplication.
C20A-T01 — From Reservation to Statistic
Problem. A page records many views. The final report is read only after all workers terminate; a panel can show an updated estimate during work. Compare AtomicLong and LongAdder. Then change the requirement: every view must receive a distinct sequence number when it arrives. Explain why the choice can change. Run AccessStatistics and indicate what makes its final output exact.
Acceptance criterion. The solution distinguishes throughput under contention and precision of concurrent reading. It recognizes that LongAdder.sum() during updates is not an atomic snapshot, while after the example's join calls the total is 8,000. To assign a distinct number to the caller it proposes an atomic operation returning the previous or new value, with range and persistence management if required.
Hint. Ask whether the caller must know the number assigned to this request or only a collective total.
Reasoned solution. For the final report alone, LongAdder is a choice to measure if concurrent updates are numerous; AtomicLong remains correct and can be simpler. In the program, every worker terminates before sum(), so nobody updates while the result read by main is formed. When instead every caller must receive a distinct sequence number, AtomicLong.getAndIncrement() directly expresses local assignment. Neither this class nor LongAdder alone guarantees a unique number across several JVMs or after a restart.
C20A-T02 — What Is the State Boundary?
Problem. In the immutable-state program, the sum of available and reserved remains five. Draw the sequence of a reader taking a reference before a successful CAS and another taking it afterwards. Now add a requirement: save the reader's name and assigned copy in a database before confirming the request. Which part can still be managed by AtomicReference and which requires another guarantee?
Acceptance criterion. The answer indicates both valid snapshots (5, 0) and (4, 1) and explains why (4, 0) does not appear if everybody reads a single immutable State. It must recognize that AtomicReference governs only the snapshot in the JVM; persistent confirmation requires a transaction or equivalent protocol in the archive.
Hint. A record is immutable only if the mutable parts it references are also handled coherently. In the proposed program both components are int, so they hide no modifiable list.
Reasoned solution. A reader calling snapshot() before replacement receives object (5, 0); one calling it afterwards receives (4, 1). The atomic variable publishes one reference at a time, and neither record changes. Adding a name to a database takes the invariant beyond that variable: CAS can succeed and writing fail. Confirmation must follow the archive's contract and handle concurrency, errors and repetitions at that level.