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.
More Constructors and the this Keyword practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!