A singleton is a design pattern used to ensure that a class has only one instance and provides a global point of access to that instance. This pattern is widely used in scenarios where it's essential to have a single point of control, such as logging, configuration settings, or database connections.
Singletons are used to:
For example, in an application where database connectivity needs to be established, it’s better to have a single connection instance shared across the application rather than creating new connections multiple times, which could be inefficient and lead to resource contention.
There are multiple ways to implement a singleton, but not all are ideal:
Eager Initialization:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
Synchronized Method:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
getInstance() is called frequently.To solve the above issues, a more efficient way of implementing a singleton is needed—one that is lazy-initialized (created only when needed) and thread-safe without the performance drawbacks of synchronization.
William Pugh is a computer scientist known for his work in improving Java's performance and concurrency patterns. He discovered a way to implement the singleton pattern in a highly efficient and thread-safe manner using a static inner class. His method leverages the Java ClassLoader's behavior to achieve optimal performance.
The Bill Pugh Singleton Design pattern solves the challenges of traditional singleton implementations:
getInstance() method is called, ensuring memory is not wasted.