Creating a thread-safe singleton in Java ensures only one instance of a class is created. The Singleton pattern is useful when you want to control object creation. To make it thread-safe, you can use synchronized blocks or the Bill Pugh Singleton Design. Double-checked locking is another way to avoid performance issues.
Here’s an example using double-checked locking:
public class Singleton {
private static volatile Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
This method ensures the instance is created only when needed and avoids locking every time. It also prevents multiple threads from creating separate instances, ensuring thread safety. Understanding these techniques can help you implement a reliable singleton.
Leave a Reply