How can static initialization order cause a subtle bug or even a deadlock?
Reviewed by Gurusankar M.
β‘ Short Answer
Static initializers run once at class load, in textual order, and can deadlock if two classes initialize each other from different threads. Circular static dependencies also yield half-initialized (null/zero) values.
βCoffee Chat Question
Concept Made Simple
βHow can static initialization order cause a subtle bug or even a deadlock?β
π§ Mind Map Answer
Remember It Faster
Class init holds a per-class lock. If thread A loads ClassX (which needs ClassY) while thread B loads ClassY (which needs ClassX), each waits on the other's init lock β deadlock.
β¨οΈHands-on Keyboard
Learn by Doing
class A { static int x = B.y + 1; }
class B { static int y = A.x + 1; } // circular init
// One of x/y reads the other while it's still 0π₯What If?
Think Beyond the Expected
An app hangs only at startup under load β how do you confirm a static-init deadlock?
Take a thread dump (jstack). You'll see two threads BLOCKED in <clinit> of different classes, each waiting on the other's class-init monitor. Fix by breaking the cycle or lazy-loading.
πReal World
Static-init deadlocks surface as intermittent startup hangs in multi-threaded bootstrapping (e.g. parallel class loading, driver registration); the thread dump shows BLOCKED <clinit> frames.
π―Interviewer's Expectation
Keywords they're listening for:
β οΈCommon Mistakes
- βCircular static dependencies between classes
- βHeavy work (I/O, network) in static initializers
- βAssuming static fields are set before another class reads them
β Best Practices
- βAvoid cross-class static cycles
- βUse the holder idiom for lazy, thread-safe singletons
- βKeep static blocks trivial; do heavy init lazily
πFollow-up Questions
- 1How does the JVM guarantee init runs once and thread-safely?
- 2Why is the initialization-on-demand holder idiom a safe lazy singleton?
- 3How do you read <clinit> frames in a thread dump?
π§©Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly β AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: JVM/Class loading (Core Java) Interview question: "How can static initialization order cause a subtle bug or even a deadlock?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
β Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission β at no extra cost to you. It helps keep Full Stack Interview Guru free.