CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 4 of 6 · 2 min read

Lazy creation

Create on first use, safely.

Sometimes the instance is expensive and may never be needed, so it is created on first use. A common first attempt looks like this.

class Unsafe {
    private static Unsafe inst;
    private Unsafe() { /* slow setup */ }
    static Unsafe get() {
        if (inst == null) inst = new Unsafe();
        return inst;
    }
}

With one thread this is fine. With several, two threads can both see null and both create an object. JCIP names this unsafe lazy initialization, and also warns that other threads may see a half-built object. In a test with eight threads released at once and a 20 millisecond setup, the unsafe class was constructed more than once, while the same class with a synchronized method was constructed exactly once. The result of such a race can differ from run to run, but the risk is real.

JCIP gives three safe ways.

  1. Make the access method synchronized. It is simple, and the cost is small if the method is not called very often.
  2. Use eager initialization: a static field with an initializer. The JVM runs static initialization once, under a lock, before any thread uses the class, so the object is visible to all threads.
  3. Use the lazy initialization holder class idiom. Put the instance in a private static nested class. The JVM initializes that class only when it is first used, so creation is lazy, and the JVM's lock makes it safe, with no synchronization on the normal path.
class Holder {
    private Holder() { }
    private static class Lazy { static final Holder INSTANCE = new Holder(); }
    static Holder getInstance() { return Lazy.INSTANCE; }
}

Two calls to getInstance() return the same object, and the constructor runs once. JCIP adds a caution: these guarantees cover the construction. If the object is mutable, its later changes still need their own locking.

Common mistake

Writing "if null then create" without synchronization, or adding a half-correct double-checked lock. Use an enum, eager creation, the holder idiom or a synchronized method.

Check yourself: 1. How can the unsafe version build two objects? 2. Why is the holder idiom lazy and thread-safe at once? 3. Does a safe singleton make its mutable fields safe?