Object declaration
There are a few ways to declare singletons in Java. Here is the most common way to define a class that has a private constructor and retrieves instances via a static factory method:
public class Singleton {
private Singleton() {
}
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
} The preceding code works fine for a single thread, but it's not thread-safe, so in some cases two instances of Singleton can be created. There are a few ways to fix it. We can use the synchronized block, presented as follows:
//synchronized
public class Singleton {
private static Singleton instance = null;
private Singleton(){
}
private synchronized static void createInstance() {
if (instance == null) {
...