xxxxxxxxxx
There are multiple ways to write thread-safe Singleton in Java, like by writing singleton using double-checked locking, by using static Singleton instance initialized during class loading.
By the way, using Java enum to create a thread-safe singleton is the most simple way
Read more: https://www.java67.com/2012/09/top-10-java-design-pattern-interview-question-answer.html#ixzz7oR7H2zOh
xxxxxxxxxx
// Java Singleton pattern, Thread safe
public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
public String getDescription() {
return "I'm a thread safe Singleton!";
}
}
public class SingletonClient {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
System.out.println(singleton.getDescription());
}
}