CoursesJVM internals for Kotlin and Android developers

Puzzle 4 · 5 of 5

How can two increments produce eight?

Follow two callers that both read seven before either saves.

All puzzles in this course

The problem

Two callers hold references to the same counter. Both want to add one. Starting at seven, could both finish their writes and leave eight?

See it

Changing shared state A reads 7 B reads 7 A saves 8 B rejected

Scroll sideways to see the full diagram.

  1. A reads the shared counter.

    Step 1 of 4
  2. B reads the same seven. Predict whether both callers will be able to save against seven.

    Step 2 of 4
  3. A changes seven to eight after checking the expected seven.

    Step 3 of 4
  4. B still expects seven. The value remains eight.

    Step 4 of 4

The building block

Write each caller's calculation on paper. A reads seven and calculates eight. B reads seven and also calculates eight. A writes eight. B writes eight. The second write used an old observation. Reading and writing a value safely as separate operations still leaves a gap between them.

A conditional write changes a value only if it still matches an expected value. Java's atomic integer offers a method that compares and writes as one indivisible step. A supplies seven as the expected value and eight as the replacement. It succeeds. B supplies the same pair and gets false because the counter already holds eight. B still owes one increment. The lab finishes it with a single operation that adds one to the current value.

EventA's observed valueB's observed valueShared counter
Both read777
A compares seven and replaces it with eight778
B compares seven and proposes eight778
B reads again, compares eight and proposes nine789

The final row assumes no other writer changes eight before B's comparison. If another writer does, B must calculate a fresh candidate again. Reporting success after B's first rejected attempt would quietly lose a requested increment. Java also supplies an atomic increment operation when adding one is the entire rule.

Now change the rule: both callers want to claim the final seat. A changes one to zero. B's original comparison fails. A fresh read for B returns zero. Retrying the business decision now means declining the reservation. Whether to try another write depends on what the operation promises. A single shared counter in one JVM only coordinates callers using that same object. Two servers with separate counters need a shared authority for the last seat.

The analogy

Two clerks copy the same tally from a shared sheet. If each replaces the tally with their pencilled answer, one arrival disappears. If the clerk checks and changes the tally while holding the sheet, the second clerk can see the mismatch.

Try it

Run the browser experiment

Optional local lab

Run the following command from the JVM source files.

java SharedCounter.java

The statements replay one possible order so you can reproduce it on every run. Before running, write down both return values and the total after each write. Then move B's read just after A's first write in the separate-writes experiment. Predict the result and update the assertion for that experiment. Reset both snapshots to seven before the conditional experiment.

Check yourself

B reads only after A writes eight. What does B calculate?

Right. B reads eight and adds one.

Not quite. B starts from the value A just stored. Re-read that part ↑

Both expect seven. A succeeds. What does B's conditional write report?

Right. The rejected write leaves eight in place.

Not quite. Seven no longer matches eight.

A claims the final seat. B's comparison fails and a fresh read returns zero. What should B do?

Right. Repeat the business decision using the fresh count.

Not quite. No seat remains to grant. Re-read that part ↑

Sources

What you now know

Checking the expected value and changing it in one indivisible step detects the stale increment.

Apply what you learned

Continue with worked examples and practice cases. When you reach the final project, make your own decisions before comparing your evidence with the worked review.

Continue to Reasoning across threads and requests → Start the final project →