CoursesJVM internals for Kotlin and Android developers
Puzzle 22 · 23 of 27
Where did 240 megabytes of objects go?
A Kotlin function creates a small object on every call, ten million times a round. With one HotSpot option the run allocates 240 megabytes a round; without it, nothing. Find out what C2 proved about the object, and why inlining from puzzle 21 had to come first.
All puzzles in this course
The problem
Puzzle 17 said objects live on the heap, and puzzle 3 that the garbage collector reclaims the ones nothing reaches. So a function that creates an object on every call should keep the collector busy:
import java.lang.management.ManagementFactory
class Stats(val visits: Int, val stars: Int) {
fun score() = visits * 2 + stars
}
fun scoreOf(visits: Int, stars: Int): Int {
val stats = Stats(visits, stars)
return stats.score()
}
fun main() {
val threads = ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean
val me = Thread.currentThread().threadId()
var sum = 0L
for (round in 1..5) {
val before = threads.getThreadAllocatedBytes(me)
for (i in 0 until 10_000_000) {
sum += scoreOf(i, round)
}
val after = threads.getThreadAllocatedBytes(me)
println("round $round: ${after - before} bytes allocated")
}
println(sum)
}
getThreadAllocatedBytes, from the JDK's ThreadMXBean, reports how many bytes a thread has allocated on the heap so far. The program prints the difference for each round of ten million calls. The -Xlog:gc option also prints a line for every garbage-collector run (GC for short):
$ java -Xlog:gc -cp out:kotlin-stdlib.jar EscapeKt
[0.005s][info][gc] Using G1
round 1: 421096 bytes allocated
round 2: 0 bytes allocated
round 3: 0 bytes allocated
round 4: 0 bytes allocated
round 5: 0 bytes allocated
500000100000000
Fifty million Stats objects, and from round 2 on, zero bytes and not one collection. A second run: 345,424 bytes in round 1, then zero again. Where did the objects go?
See it
Scroll sideways to see the full diagram.
As written, every call of scoreOf allocates a Stats on the heap, and the local stats holds a reference to it.
Step 1 of 5C2 compiles main's loop with scoreOf, the constructor and score() inlined, so it sees every use of that reference. Predict: does the object need to exist?
Step 2 of 5Escape analysis: the reference is never stored, returned or passed to a call that wasn't inlined. It is only used to read two fields.
Step 3 of 5So C2 applies scalar replacement: it keeps visits and stars as plain values in the loop and drops the allocation. The heap never sees a Stats.
Step 4 of 5Add last = stats: the reference leaves through a static field, so the object escapes and is allocated on every call, 24 bytes each on JDK 21.
Step 5 of 5
The building block
As in puzzle 21, C2 compiles one big piece of code: the loop in main, with scoreOf, the Stats constructor and score() inlined into it. Inside that code C2 can see everything the new Stats is used for. Escape analysis is C2's check of whether a new object can be reached from anywhere outside the code it is compiling. Oracle's guide lists the ways out:
| What the code does with the object | Escapes? |
|---|---|
| stores it in a static field or in a field of an object that escapes, or returns it | yes, everywhere |
| passes it to a method that was not inlined | yes, into that call |
| only reads its fields in the compiled code | no |
Here the reference in stats is only used to read visits and stars. So C2 applies scalar replacement: it keeps the two fields as plain int values in the compiled code, like local variables, and drops the allocation. No Stats object exists, so nothing is allocated and nothing needs collecting. Oracle's guide: the compiler "eliminates the scalar replaceable object allocations". Note what it doesn't do: it "does not replace a heap allocation with a stack allocation". The object isn't moved somewhere cheaper; it's gone, and only its field values remain.
Turn it off with the DoEscapeAnalysis option, and every object is real:
$ java -XX:-DoEscapeAnalysis -Xlog:gc -cp out:kotlin-stdlib.jar EscapeKt
[0.005s][info][gc] Using G1
[0.060s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 13M->1M(216M) 1.500ms
[0.072s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 35M->1M(216M) 0.674ms
[0.116s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 127M->1M(216M) 1.006ms
round 1: 240003328 bytes allocated
[0.136s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 127M->1M(216M) 0.936ms
[0.152s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 127M->1M(284M) 0.874ms
round 2: 240000000 bytes allocated
…
round 5: 240000000 bytes allocated
500000100000000
(Trimmed after round 2; the run made 9 collections in all, and a second run printed the same allocation numbers.) 240,000,000 bytes for ten million objects: 24 bytes each, two 4-byte ints plus HotSpot's own bookkeeping for every object. (JDK 27 makes that bookkeeping smaller by default, JEP 534. With the same layout turned on in JDK 25, by the UseCompactObjectHeaders option, the same run allocated 160,000,000 bytes: 16 each.) Each GC line is one collection; 127M->1M means the heap held about 127 megabytes before and 1 after, because every Stats was already unreachable. Using G1 names the collector: G1, HotSpot's default collector. How collections work is coming in a later module.
Round 1 of the default run still allocated about 400 kilobytes. Those calls ran before C2 compiled the loop: the interpreter and C1's code allocate every object.
Escape analysis needs inlining. Keep everything else and turn inlining off with the Inline option (the third command below): every round allocates 240,000,000 bytes again, because the Stats now goes to a constructor and a score() that weren't inlined, so it escapes into those calls. Or keep inlining and add one line to scoreOf, storing the object in a top-level property:
var last: Stats? = null
fun scoreOf(visits: Int, stars: Int): Int {
val stats = Stats(visits, stars)
last = stats
return stats.score()
}
A top-level var compiles to a static field, so the object escapes: 240,000,000 bytes every round, in two runs.
The edges
- Small, short-lived objects are the ones it removes. A Pair returned from a small inlined function, an iterator in a loop, a Kotlin data class used for one calculation: all can disappear. One stored in a field, a list or a lambda that escapes cannot.
- Two allocations meeting at one variable. When stats is one of two new objects, val stats = if (visits % 2 == 0) Stats(visits, stars) else Stats(stars, visits), JDK 21 allocated 240,000,000 bytes every round, in two runs: it can't remove objects whose references merge like that. JDK 22 added support for it, and on JDK 25 the same program allocated 0.
- Arrays. An array longer than 64 elements is never scalar-replaced (the EliminateAllocationArraySizeLimit option).
- Only C2 does it. Interpreted and C1-compiled code allocate every object; that's round 1's 400 kilobytes.
- Don't design around it. Whether an object is removed depends on inlining decisions (puzzle 21) that change with code size and profiles. Measure allocation, as above, instead of assuming.
- Android: ART's compilers do their own allocation removal; how much is not covered here (puzzle 18 links the Android course).
The analogy
A clerk fills in a form only to read two numbers off it a second later, then throws it away. The specialist writing the polished sheet notices that the form never leaves the desk: nobody files it, nobody sends it anywhere. So the sheet says "write the two numbers on your notepad" and the form is never printed. If the procedure files the form in a cabinet, it has to exist.
Run it yourself
Save the first program as Escape.kt, then:
kotlinc Escape.kt -d out
java -Xlog:gc -cp out:kotlinc/lib/kotlin-stdlib.jar EscapeKt
java -XX:-DoEscapeAnalysis -Xlog:gc -cp out:kotlinc/lib/kotlin-stdlib.jar EscapeKt
java -XX:-Inline -cp out:kotlinc/lib/kotlin-stdlib.jar EscapeKt
Before running the third command, predict the bytes per round.
Check yourself
Sources
- Java 21 HotSpot VM guide: Escape Analysis ("Escape analysis is a technique by which the Java HotSpot Server Compiler can analyze the scope of a new object's uses and decide whether to allocate the object on the Java heap."; "GlobalEscape: The object escapes the method and thread. For example, an object stored in a static field, stored in a field of an escaped object, or returned as the result of the current method."; "ArgEscape: The object is passed as an argument or referenced by an argument but does not globally escape during a call."; "NoEscape: The object is a scalar replaceable object, which means that its allocation could be removed from generated code."; "After escape analysis, the server compiler eliminates the scalar replaceable object allocations and the associated locks from generated code."; "It does not replace a heap allocation with a stack allocation for objects that do not globally escape.")
- OpenJDK wiki: EscapeAnalysis (Vladimir Kozlov) ("After escape analysis C2 eliminates scalar replaceable object allocations and associated locks."; "C2 does NOT replace a heap allocation with a stack allocation for non globally escaping objects.")
- The java command (JDK 21) ("-XX:+DoEscapeAnalysis Enables the use of escape analysis. This option is enabled by default. To disable the use of escape analysis, specify -XX:-DoEscapeAnalysis."; "-XX:+Inline Enables method inlining. This option is enabled by default to increase performance. To disable method inlining, specify -XX:-Inline.")
- OpenJDK source, c2_globals.hpp, jdk-21+35 (line 473: DoEscapeAnalysis, "Perform escape analysis"; line 486: EliminateAllocations, "Use escape analysis to eliminate allocations")
- JEP 534: Compact Object Headers by Default (JDK 27) ("Make compact object headers the default object header layout in the HotSpot JVM. Compact object headers reduce object headers from 96 bits down to 64 bits on 64-bit architectures")
- JDK-8287061: Support for rematerializing scalar replaced objects participating in allocation merges (Fix Version: 22)
- OpenJDK source, c2_globals.hpp, jdk-21+35, line 492 (EliminateAllocationArraySizeLimit 64, "Array size (number of elements) limit for scalar replacement")
- The JDK 25.0.5.1 runs (the if/else version: 0 bytes; +UseCompactObjectHeaders: 160,000,000 bytes per round) were made by the course's reviewer.
- Java 21 API: com.sun.management.ThreadMXBean) ("Returns an approximation of the total amount of memory, in bytes, allocated in heap memory for the thread with the specified ID.")
- All runs (default and -XX:-DoEscapeAnalysis twice each with -Xlog:gc, -XX:-Inline twice, the version with last twice, a version adding each Stats to a list, which allocated in every round, a version passing stats to a 756-byte log function (hot method too big; 240,000,000 bytes per round, two runs), and the if/else version (240,000,000 bytes per round, two runs)) were produced in this session with kotlinc 2.2.21 and OpenJDK 21.0.12 (G1 collector).
What you now know
After inlining, C2's escape analysis checks whether a new object can be reached from outside the compiled code: stored in a field, returned, or passed to a call that wasn't inlined. If not, scalar replacement keeps its fields as plain values and the object is never allocated, so the heap and the garbage collector never see it.
Answer every question above correctly to unlock the next puzzle.
Something wrong or unclear on this page? Tell me: a puzzle that didn't click is a bug in the puzzle.