Video in progress
What's the simplest thread-safe way to write a Singleton in Java?
The simplest way is eager initialization: a private static final field is created when the class is loaded, and the constructor is private. Because the JVM loads a class only once, this is thread-safe.
📖 Answer
public final class AppConfig {
private static final AppConfig INSTANCE = new AppConfig();
private AppConfig() {
// can't be created with new from outside
}
public static AppConfig getInstance() {
return INSTANCE;
}
}
There's no synchronization here, because the static field is filled during class initialization, and the JVM does that on one thread, once.
The downside is that the object gets created even if it's never needed. If it's heavy (say, it reads a large file), you need a lazy variant. In that case people usually use the "holder" idiom:
public final class Heavy {
private Heavy() {}
private static class Holder {
static final Heavy INSTANCE = new Heavy();
}
public static Heavy getInstance() {
return Holder.INSTANCE; // Holder is loaded only here
}
}
In a Spring project you almost never write a Singleton by hand: the container itself hands out one instance of a bean.
Sign up to mark studied questions and save your progress.