Scrivio Interview library
DesignPrincipal7 min read · updated 12 November 2026

Static initialization and singletons have caused startup failures, test pollution and deadlocks across your organization's services for years. With Spring dependency injection, CDS and AOT caches available, what rules on static state and class initialization would you set org-wide?

Static initializers run once, on first use, under a per-class lock, so a failure there turns into a permanent NoClassDefFoundError and two classes that need each other can deadlock. I would allow only static final constants and pure, computed tables in static state, forbid I/O, network calls and configuration reads in static initializers, move all of that into Spring beans with an explicit lifecycle, and enforce the rules with static analysis, review checklists and a startup-time budget per service.

Why this question is asked

When a problem has hit many services for years, the issue is no longer one bad class; it is a missing rule. Static initialization is an attractive place to put setup code because it runs automatically and needs no wiring, and that is exactly why it causes trouble at scale: it runs at an unpredictable moment, on whichever thread gets there first, with no way to retry. Interviewers ask this design question at a senior level to see whether we can explain the mechanism and turn it into rules people will follow. In this answer, we will recap how class initialization works, see how it produces each of the three failures, set out the rules, explain how Spring, CDS and AOT caches change the picture, and finish with how to enforce the rules.

1A Quick Recap of Class Initialization

A class is initialized the first time it is actively used: when we create an instance, call a static method, or read a static field that is not a compile-time constant. Initialization runs the static field initializers and static blocks in source order, as one hidden method called clinit.

The JVM guarantees this happens exactly once, even when many threads touch the class at the same time. It does so with an initialization lock per class. The first thread runs clinit, and every other thread that needs the class waits until it is done. That guarantee is useful, and the same lock and the same once-only rule are behind every failure in the question.

2How Static Initialization Produces Each Failure

Startup failures come from the once-only rule. If clinit throws, the first caller gets ExceptionInInitializerError with the real cause. The class is then marked as failed for the life of its class loader, and every later use gets NoClassDefFoundError: Could not initialize class, which hides the cause. There is no retry, so a config server that was down for two seconds at startup breaks the service until it restarts.

Deadlocks come from the lock. If class A's static block uses class B, and B's static block uses A, then a thread that starts with A and another that starts with B can each hold one lock and wait for the other forever.

Java
class A {
static final Object X;
static { X = B.Y; } // thread 1 holds A's init lock and waits for B
}
class B {
static final Object Y;
static { Y = A.X; } // thread 2 holds B's init lock and waits for A
}
// thread 1: A.X thread 2: B.Y -> both threads hang, no exception, no timeout
Step throughTwo threads initialize two classes that need each other
Thread 1class Aclass BThread 2
first use of A: take A's init lock
first use of B: take B's init lock
A's static block reads B.Y: wait for B's lock
B's static block reads A.X: wait for A's lock
blocked forever
blocked forever

6 messages in order. Play them, or step through them one at a time.

A thread dump shows both threads waiting in class initialization; nothing ever times out.

Test pollution comes from the lifetime. A static field lives as long as its class loader, which in a test run is usually the whole JVM. Tests that put data into a static cache, a static registry or a static clock leave it there for every test that runs afterwards, and the result depends on test order.

3The Rules I Would Set

The rules follow from the mechanism. First, static state is allowed only for static final constants and for pure computed tables: values computed from code alone, such as a lookup array or an immutable Map.of(...), with no input from the outside world. Those cannot fail differently from one environment to the next, and they make no calls into other classes' setup.

Second, static initializers must not do I/O, network calls, configuration or environment reads, or lookups of other services. Anything that can fail or that depends on the environment belongs in a Spring bean, where it has an explicit lifecycle: constructor injection for dependencies, @PostConstruct or a SmartLifecycle for startup work, and a clear error message from the context when it fails.

Third, no mutable static state: no static caches, no static registries and no static singletons with setters. If something must be shared, it is a singleton bean, which Spring already provides, and tests get a fresh one per context. Fourth, no hand-written singletons with getInstance() for anything that has dependencies; the container is the one place where object lifetimes are decided.

Static state rules
PatternRuleWhy
static final int MAX = 50Allowedcompile-time constant, nothing can fail
static final Map.of(...) or computed arrayAllowedpure computation, same in every environment
static block reading a file or env varForbiddenfailure becomes permanent NoClassDefFoundError
static HTTP or JDBC callForbiddenslow, can fail, and runs on an unknown thread
static mutable cache or registryForbiddenleaks between tests, not thread-safe by default
getInstance() singleton with dependenciesReplace with a beanlifecycle and wiring belong to Spring

Each rule also has a clear exception path. A team that really needs a lazy static, for example in a library that cannot depend on Spring, uses the holder idiom with pure computation and writes down why.

4How Spring, CDS and AOT Caches Change the Picture

Spring dependency injection removes the main reason people wrote static singletons: they needed one shared instance reachable from anywhere. A singleton bean gives us that, with ordering decided by declared dependencies instead of by whichever class happens to be touched first, and with a startup failure that names the bean and the cause.

Class Data Sharing and the AOT cache (JEP 483 in JDK 24, with simpler command-line use in Java 25) make class loading and linking cheaper by storing that work from a training run. They reward code whose classes can be loaded and linked early without side effects, and they do not run our own static initializers ahead of time, so a slow clinit is still slow. The same holds for Spring AOT and native images: GraalVM must decide whether each class is initialized at build time or at run time, and a static block that reads the environment either breaks the build or must be forced to run time with extra configuration. Code that keeps static state pure is the code that benefits from all three with no extra work.

5Enforcing the Rules

Rules that live only in a wiki fade. We put them into the build. ArchUnit tests in a shared test library can forbid static fields of mutable collection types and calls to file, network or System.getenv APIs from static initializers. Error Prone or Sonar rules can flag mutable static fields. The pull request template carries a short checklist item for new static state.

We also measure. Each service reports its startup time to the same dashboard, and a jump of more than, say, 20 percent between releases opens a ticket. Startup logs with -Xlog:class+init, or a JFR recording of startup, show which initializers are slow. Existing violations are listed and burned down by teams over a few quarters, while new code is held to the rules from day one.

6Follow-up questions

Is the holder idiom still acceptable under these rules?

Yes, when the value is pure. The holder idiom puts a static final field in a private nested class, so it is initialized only on first use and the JVM's init lock makes it thread-safe. It is a good way to defer an expensive pure computation. It is not a loophole for I/O, because a failure in the holder's static initializer still makes the holder permanently unusable.

How do you find an initialization deadlock in production?

Take a thread dump with jcmd <pid> Thread.print or jstack. The stuck threads show frames inside the static initializers of the classes involved, and since JDK 21 or so the dump can also say a thread is waiting on class initialization by another thread; check your version for the exact wording. The fix is to break the cycle so neither class needs the other during initialization.

What about enum constants and static loggers?

Both are fine. Enum constants are static final values built from code, and a static final Logger is effectively a constant obtained from a logging factory that is designed to be called during class initialization. The rules target environment-dependent work and mutable state, not these idioms.

7Conclusion

In this answer, we saw that static initializers run once, lazily, under a per-class lock, and that this explains permanent NoClassDefFoundError failures, initialization deadlocks between classes that need each other, and state that leaks between tests. The rules follow from it: only constants and pure computed tables in static state, no I/O or configuration in static initializers, shared objects as Spring beans, and enforcement through ArchUnit, analysis tools, review checklists and a startup-time budget, which also keeps services ready for CDS, AOT caches and native images.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start from the mechanism, because the rules follow from it. A static initializer runs once, on first use, on whatever thread gets there first, under a per-class init lock.

Then, if they want more

If it throws, the first caller gets ExceptionInInitializerError and every later caller gets NoClassDefFoundError for the life of the class loader, so a two-second network blip at startup becomes a broken service. If two classes need each other during initialization, two threads can each hold one lock and deadlock with no timeout.

And static fields live as long as the class loader, so mutable static state leaks between tests.

So the rules are: static state only for static final constants and pure computed tables; no I/O, network calls, environment or config reads in static initializers; no mutable static caches or registries; and anything with dependencies or lifecycle is a Spring bean, with startup work in PostConstruct or a lifecycle bean so failures are explicit and named.

This also keeps us ready for CDS, the AOT cache and native images, which work best when static initialization is pure.

I would enforce it with ArchUnit rules in a shared test library, Sonar or Error Prone checks, a review checklist item, and a startup-time metric per service with an alert on regressions, and burn down existing violations team by team.

About this answer

Last updated
12 November 2026
Versions it names
Java 21, Java 24, Java 25
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Static initialization and singletons have caused startup failures, test pollution and...": https://scrivio-interview-library.netlify.app/java/classes-and-objects/f6d8ec69ee/