How many ways can you write a singleton in Java, and what are the trade-offs?
There are about five ways to write one, and they differ mostly in how they handle the thread safety and how they handle the process being saved and loaded again.
The first way is an eager static field. The instance is made when the class is loaded, and it is simple. The problem is that it is made even if nobody ever asks for it.
The second way is a lazy method that checks a flag. It is simple, and it is not safe when more than one thread asks at the same time, because two instances can be made.
The third way is double checked locking. The method checks the flag, and only then takes a lock and checks it again. It works, but only if the field is volatile.
The fourth way is the holder idiom, and it is the best one for most cases. The instance lives in a static final field of a private nested class, and the nested class is only loaded when somebody asks for the instance.
The fifth way is an enum, and it is the best one when the object might be saved and read back, because the virtual machine makes sure there is only one copy of an enum value even then.
public class Main {
public static void main(String[] args) {
System.out.println("eager : " + EagerConfig.INSTANCE.getName());
System.out.println("holder : " + HolderConfig.getInstance().getName());
System.out.println("enum : " + EnumConfig.INSTANCE.getName());
System.out.println("the same instance : " + (HolderConfig.getInstance() == HolderConfig.getInstance()));
}
}
class EagerConfig {
static final EagerConfig INSTANCE = new EagerConfig();
private final String name = "eager";
String getName() {
return this.name;
}
}
class HolderConfig {
private static final class Holder {
static final HolderConfig INSTANCE = new HolderConfig();
}
static HolderConfig getInstance() {
return Holder.INSTANCE;
}
private final String name = "holder";
String getName() {
return this.name;
}
}
enum EnumConfig {
INSTANCE;
private final String name = "enum";
String getName() {
return this.name;
}
}
So the trade-offs are these. The eager version is simple and safe, but it always makes the instance. The lazy method is simple but not safe. The double checked locking is safe and lazy, but it is harder to read and it needs a field that is volatile. The holder idiom is safe, lazy, simple to read, and it has no lock at all. The enum is safe and it survives being saved, but it cannot take the arguments that a constructor would need.
The next question in this topic looks at the safe lazy versions in detail.