Consider the below code snippet:
public class DbSingleton {
private static volatile DbSingleton instance = null;
private DbSingleton() {
if (instance != null) {
throw new RuntimeException("Use getInstance()");
}
}
public static DbSingleton getInstance() {
if (instance == null) {
synchronized (DbSingleton.class) {
if (instance == null) {
instance = new DbSingleton();
}
}
}
return instance;
}
}
Why is the above preferred to declaring getInstance() as synchronized? What does it mean when a method is declared as synchronized? Will it synchronize the entire class and slow down the performance?