← Java roadmap

Topic 29 of 30 · Expert

Implement thread-safe lazy initialization with the holder idiom

Return the same lazily initialized Registry instance to every ordinary caller in one class-loader domain.

ExpertSenior · 5–8 yearsConcurrency

Java 17+; compile each complete program as Main.java.

Problem statement

Return the same lazily initialized Registry instance to every ordinary caller in one class-loader domain.

A service-wide immutable registry is initialized on first use.

Input: Concurrent calls to Registry.instance().

Output: Same object identity.

  • No reflection or custom deserialization attack model.
  • One class-loader domain.
  • Registry contains no mutable shared state.

Sample 1

Input: two concurrent calls
Output: true for identity comparison

Both see the initialized holder instance.

Sample 2

Input: no calls
Output: holder not initialized by instance access

Initialization occurs on first active use of Holder.

Brute-force solution

Synchronize the whole accessor to guard creation, incurring repeated locking.

O(1) after one-time initialization; initialization may wait for another thread.

import java.util.concurrent.*;
class Main {
static class Registry {private Registry(){} private static class Holder {static final Registry INSTANCE=new Registry();}static Registry instance(){return Holder.INSTANCE;}}
public static void main(String[] args) throws Exception {
ExecutorService pool=Executors.newFixedThreadPool(2);
try{Future<Registry> a=pool.submit(Registry::instance),b=pool.submit(Registry::instance);if(a.get()!=b.get())throw new AssertionError();System.out.println(a.get()==b.get());}finally{pool.shutdown();}
}
}
Optimized solution

JVM class initialization supplies thread-safe publication for the nested holder.

  1. Hide construction.
  2. Create the instance in a nested static holder.
  3. Return Holder.INSTANCE.
import java.util.concurrent.*;
class Main {
static class Registry {private Registry(){} private static class Holder {static final Registry INSTANCE=new Registry();}static Registry instance(){return Holder.INSTANCE;}}
public static void main(String[] args) throws Exception {
ExecutorService pool=Executors.newFixedThreadPool(2);
try{Future<Registry> a=pool.submit(Registry::instance),b=pool.submit(Registry::instance);if(a.get()!=b.get())throw new AssertionError();System.out.println(a.get()==b.get());}finally{pool.shutdown();}
}
}
Complexity analysis

Time: O(1) after one-time initialization; initialization may wait for another thread.

Auxiliary space: O(1) singleton state.

Test cases
  • Concurrent first access.
  • Repeated access.
The supplied main submits two concurrent accesses and asserts reference identity.
Common mistakes
  • Double-checked locking without correct volatile publication.
  • Assuming singleton scope spans all class loaders.
Key takeaways
  • Define singleton scope.
  • Use class initialization guarantees.
  • Mutable singleton state still needs coordination.
Follow-up challenges
  • When is an enum singleton preferable?
  • Why might dependency injection be better?
Practise Java with the AI mentor

Can't find a Java topic you need for exams or placements? Request it and we'll add it.