LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Constructors Programs · Question 6

Thread-safe singleton with a holder class in Java Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Implement a lazily created, thread-safe singleton using the initialization-on-demand holder idiom, and show that it is created only once even when eight threads request it at the same time.

Solution
Main.java
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

final class Registry {
    static final AtomicInteger CONSTRUCTED = new AtomicInteger();

    private Registry() { CONSTRUCTED.incrementAndGet(); }

    private static final class Holder {          // loaded only when getInstance() first runs
        static final Registry INSTANCE = new Registry();
    }

    static Registry getInstance() { return Holder.INSTANCE; }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("before: " + Registry.CONSTRUCTED.get());
        Set<Registry> seen = ConcurrentHashMap.newKeySet();
        Thread[] threads = new Thread[8];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> seen.add(Registry.getInstance()));
            threads[i].start();
        }
        for (Thread t : threads) t.join();
        System.out.println("after: " + Registry.CONSTRUCTED.get() + ", distinct instances: " + seen.size());
    }
}

Output Verified by compiling and running

before: 0
after: 1, distinct instances: 1

The JVM initialises the Holder class exactly once and thread-safely, so the private constructor runs once without any locking code.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links