Junior
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 has several errors and shortcomings:
- The
instancefield is declared asstatic final, but not initialized, which will cause a compilation error. - The constructor is
public, allowing new instances to be created outside the class, violating the Singleton pattern. - The
getInstance()method is not static, but it should be static to be called without creating an object. - The double-checked locking logic is implemented incorrectly: it first checks
instance != null, then inside synchronization, it checksinstance == null— this is pointless.
A correct implementation of a thread-safe, lazily initialized Singleton with double-checked locking in Java might look like this:
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// private constructor
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Here, volatile ensures correct memory visibility, and the getInstance() method is static and implements thread-safe lazy initialization.