Middle+
What needs to be changed in this code to have a correct thread-safe implementation of the Singleton pattern? public class Singleton { private static final Singleton instance; public Singleton() { } public Singleton getInstance() { if (instance != null) { synchronized (instance) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
sobes.tech AI
Answer from AI
The provided code contains several errors:
- The
instancefield is declared asfinal, but it is not initialized immediately — this is impossible. - In the
getInstance()method, the check and synchronization are done incorrectly.
A correct thread-safe implementation with lazy initialization and double-checked locking looks like this:
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// private constructor
}
public static Singleton getInstance() {
if (instance == null) { // first check without synchronization
synchronized (Singleton.class) {
if (instance == null) { // second check inside synchronized
instance = new Singleton();
}
}
}
return instance;
}
}
Key points:
instanceshould bestatic volatilefor correct visibility of changes across threads.- Synchronization occurs on the class, not on the instance.
- The constructor is private to prevent creating instances from outside.