CoursesJVM internals for Kotlin and Android developers
Puzzle 12 · 13 of 27
Why is it zero?
Puzzle 11 showed that preparation fills static fields with defaults and initialization runs the static code once. Here is what goes wrong when that code reads a field before the line that sets it.
All puzzles in this course
The problem
Puzzle 11 ended with initialization: the JVM runs a class's static code once, at its first real use. This Kotlin class compiles without a warning and prints 0, not 20:
class Settings {
val doubled = limit * 2
companion object {
val shared = Settings()
val limit = 10
}
}
fun main() {
println(Settings.shared.doubled) // prints 0
}
limit is clearly 10 in the source. Where does the 0 come from? And why doesn't anything crash?
See it
Scroll sideways to see the full diagram.
Preparation (puzzle 11) gives every static field its default: limit is 0, shared is null. Now initialization runs the static code, top to bottom.
Step 1 of 6The first line creates a Settings object, which runs its constructor before the next static line can run.
Step 2 of 6The constructor computes doubled = limit * 2. Predict: which value of limit does it read?
Step 3 of 60, the default: the line that writes 10 hasn't run yet. doubled is 0, and the object goes into shared.
Step 4 of 6Only now does limit become 10. No error, no warning: shared.doubled stays 0 for the rest of the program.
Step 5 of 6Write limit first and doubled is 20. A const val would work in any order: its value is copied in at compile time (puzzle 6).
Step 6 of 6
The building block
All the static code of a class, every static field's value and every static block, is compiled into one method that the class file calls <clinit> and javap prints as static {}. It is the class's static initializer, and initialization (puzzle 11) means running it, once. For Settings it holds the companion's fields too (Kotlin stores a companion's properties as static fields of the outer class, puzzle 8):
static {};
Code:
0: new #28 // class Settings$Companion
3: dup
4: aconst_null
5: invokespecial #31 // Method Settings$Companion."<init>":(Lkotlin/jvm/internal/DefaultConstructorMarker;)V
8: putstatic #35 // Field Companion:LSettings$Companion;
11: new #2 // class Settings
14: dup
15: invokespecial #36 // Method "<init>":()V
18: putstatic #24 // Field shared:LSettings;
21: bipush 10
23: putstatic #12 // Field limit:I
26: return
putstatic writes a static field, the opposite of getstatic. The lines run in the order they're written in the source. Offset 15 runs Settings' constructor, which computes doubled from limit. limit has existed since preparation, holding the default 0, and the putstatic that writes 10 is at offset 23, later. The constructor reads 0, and doubled is 0. Nothing is wrong from the JVM's point of view: the field exists and has a value.
The rule: inside a static initializer, a static field read before the line that writes it gives its default value: 0, false or null. It isn't an error, so nothing tells you. The same happens in Java (this class prints 0 10):
public class Config {
static final Config shared = new Config();
static int limit = 10;
final int doubled;
Config() { doubled = limit * 2; }
}
The fixes, both checked by running them: write limit before shared, and doubled is 20; or make it const val limit = 10, which is copied into the constructor's bytecode at compile time (puzzle 6), so there's no field to read too early, and doubled is 20 in any order. In general, keep a static initializer from calling code that reads other statics of the same class. Both compilers reject the plainest case, a direct read of a later field on an earlier line (kotlinc says "variable 'b' must be initialized", javac "illegal forward reference"), but neither looks inside a constructor or a function the line calls, which is how Settings slipped past.
The edges
- Two classes that need each other. If A's static code uses B, and B's static code uses A, the thread initializing A starts B, and B's read of A sees A's defaults: the JVM treats the second request for A as already under way and doesn't wait for itself. The result depends on which class is touched first.
- Threads wait for each other. If another thread is initializing the class, the JVM makes the next thread wait until it finishes. That's why a Kotlin object is a safe way to create one shared instance: its static initializer runs once, even with many threads.
- A Kotlin object is initialized at first access, a companion object when its outer class is initialized, matching a Java static initializer, as the Kotlin docs put it.
The analogy
A new office opens and the clerk works through the opening checklist from the top. Line 1: "Print the welcome sign: the opening hours are twice the posted staff count." Line 2: "Post the staff count: 10." When line 1 runs, the board still shows the blank the painters left, 0, so the sign says 0 hours, and nobody reprints it.
Run it yourself
Save the Settings class and main from the top of this page as Settings.kt. A Kotlin program needs Kotlin's standard library, kotlin-stdlib.jar, in the list after -cp. That file is a jar: one zip file holding class files, which a -cp list can name just like a folder. It sits in the lib folder next to the bin folder that holds kotlinc, so the command finds it from wherever kotlinc is installed (or run the program with the kotlin command, which adds the library for you):
kotlinc Settings.kt -d out
java -cp "out:$(dirname "$(command -v kotlinc)")/../lib/kotlin-stdlib.jar" SettingsKt
kotlin -cp out SettingsKt
javap -classpath out -c -p Settings
Before running, write down what you expect each java line to print. Then swap the two companion lines and predict the output. Then make limit a const val and predict again.
Check yourself
Sources
- JVM specification, 2.9.2 Class Initialization Methods ("A class or interface has at most one class or interface initialization method and is initialized by the Java Virtual Machine invoking that method (§5.5)."; "It has the special name <clinit>.")
- Java language specification, 12.4.2 Detailed Initialization Procedure ("Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.")
- JVM specification, 5.5 Initialization ("If the Class object for C indicates that initialization is in progress for C by some other thread, then release LC and block the current thread until informed that the in-progress initialization has completed"; "If the Class object for C indicates that initialization is in progress for C by the current thread, then this must be a recursive request for initialization. Release LC and complete normally.")
- Kotlin docs: Object declarations and expressions ("Object declarations are initialized lazily , when accessed for the first time. A companion object is initialized when the corresponding class is loaded (resolved) that matches the semantics of a Java static initializer.")
- The outputs (0, 0 10, and 20 after either fix) were produced in this session with kotlinc 2.2.21 and OpenJDK 21.0.12.
What you now know
A class's static code runs once, top to bottom, as one method the class file calls <clinit>. Any read of a static field whose line hasn't run yet silently sees the default value (0, false or null), with no error and no warning.
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.