Skip to content
Java 27 LazyConstant: Fix 6s Startup Delay Caused by Eager static final Initialization

Java 27 LazyConstant: Fix 6s Startup Delay Caused by Eager static final Initialization

The author traces a 6-second Java service startup delay to eager initialization of large objects via static final fields, demonstrates how Java 27's LazyConstant API enables thread-safe, one-time lazy initialization with constant semantics, and explains when to use it versus Spring @Lazy, caches, or double-checked locking.

LuTiao Programming
LuTiao Programming
LuTiao Programming

While troubleshooting a Java service that took 8–9 seconds to pass health checks, the author discovered that nearly 6 seconds were spent before Spring even started. The culprit: several static final fields that eagerly loaded large objects — such as an 80 MB risk dictionary, PDF template parsers, address dictionaries, and compiled rule expressions — during class initialization. These objects were expensive to create but rarely used (e.g., only needed for advanced risk checks, not regular queries).

The Problem with static final for Expensive Objects

A typical pattern looked like this:

public final class RiskRuleRepository {
    private static final RiskDictionary DICTIONARY = loadDictionary();
    private static RiskDictionary loadDictionary() {
        // read ~80MB rule file, parse, build index, compile rules
        return RiskDictionaryLoader.load();
    }
    public static RiskDictionary dictionary() { return DICTIONARY; }
}

Although static final ensures immutability and single initialization, it forces initialization at class-loading time — even if the object is never used. The author found multiple such objects, each adding hundreds of milliseconds to startup.

Evolution of Lazy Initialization in Java

1. Synchronized + Null Check

private static RiskDictionary dictionary;
public static synchronized RiskDictionary dictionary() {
    if (dictionary == null) {
        dictionary = RiskDictionaryLoader.load();
    }
    return dictionary;
}

Drawbacks: field cannot be final; every access pays synchronization cost; callers might bypass the accessor and read the field directly.

2. Double-Checked Locking

private static volatile RiskDictionary dictionary;
public static RiskDictionary dictionary() {
    RiskDictionary value = dictionary;
    if (value == null) {
        synchronized (RiskRuleRepository.class) {
            value = dictionary;
            if (value == null) {
                value = RiskDictionaryLoader.load();
                dictionary = value;
            }
        }
    }
    return value;
}

Works but clutters business code with concurrency boilerplate ( volatile, double null-check, synchronized, local variable, safe publication).

Java 27 LazyConstant (JEP 531, Third Preview)

Java 27 introduces java.lang.LazyConstant to express the exact semantics: "initialize on first use, once, thread-safe, then never change."

private static final LazyConstant<RiskDictionary> DICTIONARY =
    LazyConstant.of(RiskDictionaryLoader::load);

public static RiskDictionary dictionary() {
    return DICTIONARY.get();
}
LazyConstant.of(...)

does not execute the loader.

First call to DICTIONARY.get() runs the loader; concurrent callers wait.

Subsequent calls return the same initialized value.

JDK guarantees atomic initialization, at-most-once execution, and safe publication.

Not a Supplier

A plain Supplier<T> re-executes on every get(). LazyConstant embodies constant semantics: uninitialized → initialize once → forever return that value.

When to Use LazyConstant

Best for objects that are:

Expensive to initialize (large dictionaries, compiled rule sets, precomputed indexes, complex parsers, template collections, static mapping tables, immutable config snapshots).

Immutable for the JVM lifetime.

Not managed by Spring (use @Lazy for Spring beans).

Not remote/dynamic (no retry, no refresh).

Anti-patterns: remote config that might timeout (failure becomes permanent), data requiring eviction/expiration (use Caffeine/Redis), or huge objects that would pin memory (2 GB loaded once stays forever).

Lazy Collections: Map.ofLazy , List.ofLazy , Set.ofLazy

Java 27 also provides lazy maps/lists/sets. Example: 50 industry rule templates, but each instance serves only 2–3 tenants. With

Map.ofLazy(Set<String>, Function<String, RuleSet>)

, each template compiles on first access; unused templates never compile.

Trade-offs: Startup Time Moves to First Use

Lazy initialization shifts the 6-second cost from startup to the first request that needs the object. If that latency is unacceptable (e.g., 8 seconds), pre-warm asynchronously after the service is Ready:

if (advancedModeEnabled) {
    AdvancedRiskEngine.warmup(); // calls RULES.get()
}

Key difference: initialization timing becomes controllable — core service starts fast, optional capabilities load on demand or via explicit warm-up.

Kubernetes Scaling Benefits

In containerized environments, rolling out 15 new pods simultaneously no longer triggers a "startup storm" of parallel dictionary loads, rule compilations, CPU spikes, config-service QPS bursts, and disk I/O contention. Startup performance becomes part of elastic scaling capability.

Preview Status & Migration

LazyConstant

is still a Preview API in JDK 27 (third preview). Requires --enable-preview at compile and runtime. Not recommended for blind production adoption yet, but teams should audit existing static final fields that hide expensive I/O, parsing, or compilation.

Three-Category Classification After Refactoring

Cheap & always used: keep static final.

Expensive, immutable, possibly unused: migrate to LazyConstant.

Needs expiration, refresh, or eviction: use a proper cache (Caffeine, Redis).

Spring-managed beans: continue with @Lazy.

Conclusion

The real win isn't just reducing startup from 9 s to 3 s; it's gaining the ability to question why an object must be created at startup. For containerized Java services, deferring expensive immutable objects until first business use — or controlled warm-up — improves startup latency, baseline memory, and scale-out resilience. Java 27's LazyConstant finally gives this pattern a standard, JVM-supported API with constant semantics.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

startup performancelazy initializationdouble-checked lockingstatic finalLazyConstantJEP 531Java 27Kubernetes scaling
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.