Recently I was in an interview and they asked me Java Singleton pattern. So I wrote down the code for the double-check locking mechanism which is as follows:
public class MultiThreadedSingleton {
private static volatile MultiThreadedSingleton instance;
private MultiThreadedSingleton() {
}
public static MultiThreadedSingleton getInstance() {
if (instance == null) {
synchronized (MultiThreadedSingleton.class) {
if (instance == null) {
instance = new MultiThreadedSingleton();
}
}
}
return instance;
}
}
The pattern was fine but the interviewer said that I don't need to do locking. Then he asked me to write eager initialization code to which he said that you don't need any synchronized block. Which is true.
Shouldn't choosing of Singleton pattern depend upon the situation? If initialization task is heavy, I can use multi-threaded lazy initialization but if the initialization is light, I can go for eager initialization. Any guess?
Thanks