liveBook · Manning

Class initialization monitor

As explained in 100 Java Mistakes and How to Avoid Them

A class initialization monitor is the JVM synchronization mechanism on which threads wait while a class initializer is running.

A class initialization monitor is the JVM synchronization mechanism that threads wait on while a class initializer runs. Cyclic initialization can deadlock when two threads initialize mutually dependent classes. section 3.9.3

A cyclic initialization deadlock

Parallel initialization of A and B can leave A waiting for B while B waits for A. The application may freeze only under concurrency, making the defect intermittent and difficult to reproduce. section 3.9.3

"main" #1 prio=5 os_prio=0 …
   java.lang.Thread.State: RUNNABLE
    at com.example.B.<clinit>(Test.java:22)
    - waiting on the Class initialization monitor for com.example.A
    at com.example.Test.lambda$main$1(Test.java:8)
    at com.example.Test$$Lambda$2/0x0000000800c00c18.run(Unknown Source)
…
"ForkJoinPool.commonPool-worker-1" #23 daemon prio=5 os_prio=0 …
   java.lang.Thread.State: RUNNABLE
    at com.example.A.<clinit>(Test.java:14)
    - waiting on the Class initialization monitor for com.example.B
    at com.example.Test.lambda$main$0(Test.java:8)
    at com.example.Test$$Lambda$1/0x0000000800c00a00.run(Unknown Source)

The thread dump exposes the cycle directly: each thread waits on the other class's initialization monitor. section 3.9.3

Use jstack with the stuck process identifier and inspect <clinit> frames. Break cyclic initialization dependencies; static analyzers can detect the superclass-accessing-subclass pattern, but not every cycle. section 3.9.3

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains <clinit> frames, monitor waits, cyclic dependencies, and diagnostic output, but does not detail JVM initialization algorithms.
Examples
Uses parallel A and B initialization, a jstack thread dump, and a superclass field typed as its subclass.
What it assumes
Assumes familiarity with Java classes, static initialization, inheritance, threads, and process diagnostics.
What you can do after
Diagnose deadlocks with jstack and recognize cyclic initialization patterns that static analyzers may report.
How it connects
Connects class initialization with deadlock, static initialization, inheritance, thread dumps, and static analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.