Junior — Middle
How to implement thread-safe singleton pattern in a multithreaded environment?
sobes.tech AI
Answer from AI
To create a thread-safe singleton instance in Java, the pattern with lazy initialization and double-checked locking is often used. This avoids unnecessary synchronization after the instance is created.
Example implementation:
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// private constructor
}
public static Singleton getInstance() {
if (instance == null) { // first check without locking
synchronized (Singleton.class) {
if (instance == null) { // second check inside synchronized block
instance = new Singleton();
}
}
}
return instance;
}
}
Key points:
volatileguarantees visibility of changes to the instance across all threads.- The first check
if (instance == null)avoids locking after initialization. - The second check inside
synchronizedprevents multiple instances from being created during concurrent access.
Alternatively, static inner class initialization can be used, which is also thread-safe and simpler:
public class Singleton {
private Singleton() {}
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}