Junior — Middle
How to implement the Singleton pattern in Java?
sobes.tech AI
Answer from AI
The Singleton pattern guarantees that a class has only one instance and provides a global point of access to it.
In Java, this can be implemented in several ways. One simple and thread-safe option is to use lazy initialization with the synchronized keyword or to use a static nested class.
Example using a static nested class:
public class Singleton {
private Singleton() {
// private constructor
}
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
This approach guarantees that the instance is created only upon the first call to getInstance(), and it is thread-safe without using synchronized.