JVM internals for Kotlin and Android developers · Final project

Explain one run from class file to shared counter

Trace a small program before running it. Defend which values belong to method frames, which objects remain reachable and which concurrent schedules lose an increment.

Before you start

Complete all five JVM puzzles. Know the difference between a primitive value, a reference value, a frame and an object.

Use the JVM workbench or labs/jvm/Bookmark.java. The program makes a Counter(7), assigns first and second to it, calls edit(second), then clears second. The edit method writes 8 through its argument and rebinds the argument to a new Counter(99).

Run the investigation

  1. Sketch the caller’s slots before and after edit. Give each heap object its own label. Predict every line printed by Bookmark before running it.
  2. Trace increment(7) as a separate frame. Explain which operation puts eight back in the caller, and why original still prints seven.
  3. Identify the earliest point where the Counter(99) can become unreachable in this example. Explain what clearing second changes while first still exists.
  4. Switch to the shared-counter puzzle. Starting from seven, schedule two reads before either write. Then repeat with a conditional atomic change and retry the failed increment.

Evidence to keep

Compare with a worked review

Call the first object C1. first and second both contain references to C1. The callee receives a copy of that reference. Writing inside.value changes C1 to 8. Assigning inside to a new C2 changes only the callee’s local reference. Once no live reference to C2 is needed it may become unreachable; nothing in this program fixes the time of collection.

increment receives the primitive 7, computes 8 and returns that value for printing. It never writes the caller’s original slot. Clearing second leaves first pointing to C1, so the final read through first still returns 8.

Two separate read-add-write sequences can both read 7, compute 8 and store 8. A conditional atomic change from 7 to 8 lets one succeed. The second observes failure, reads the new value and tries 8 to 9. This schedule concerns a shared counter across callers; rebinding a reference in one frame is a separate mechanism.

Change one assumption

Change edit so that it rebinds inside to Counter(99) before writing inside.value = 8. Which printed lines change?

Check your reasoning

The write now changes C2. Neither caller reference was redirected, so C1 stays at 7. The three lines become “7 8”, “7 7” and “7”. Reassigning the local argument never modified first or second.

Return to course outline