Loading...
Loading...
In many real-world applications, certain objects should only be instantiated once during the lifecycle of the program — for example, a database connection pool, a configuration manager, or a logging service. The Singleton design pattern ensures that a class has only one instance and provides a global point of access to it.
However, in a multi-threaded environment, naïve implementations can lead to race conditions where multiple threads simultaneously create separate instances. Your task is to implement a thread-safe Singleton class in Java.
Implement a Singleton class with the following requirements:
You must implement the following method:
public static Singleton getInstance()
For testing purposes, a simulation harness will:
Singleton.getInstance().System.identityHashCode())."PASS" if all hash codes are identical, "FAIL" otherwise.Input: An integer N — the number of concurrent threads requesting the instance.
Output: "PASS" if all threads received the same instance, "FAIL" otherwise.
Input: N = 1
Output: "PASS"
Explanation: Only one thread requests the instance. Trivially, one unique instance is created and returned.
Input: N = 10
Output: "PASS"
Explanation: Ten threads concurrently call getInstance(). A correct thread-safe implementation ensures all threads receive the same instance reference.
Input: N = 100
Even under heavy concurrency with 100 threads racing to get the instance, only one instance is ever created.
1 <= N <= 500 All threads are launched concurrently using a CountDownLatch The Singleton class must be lazily initialized No external concurrency libraries allowed beyond java.util.concurrent
"PASS"if (instance == null) check followed by instantiation is not safe under concurrency — two threads may both see null and both create instances.getInstance() fully synchronized is thread-safe but introduces a performance bottleneck on every call.instance == null twice — once outside and once inside a synchronized block — to minimize locking overhead. Use the volatile keyword on the instance field to prevent instruction reordering by the JVM.1 <= N <= 500CountDownLatch.Singleton class may not use any external libraries.