In my last interview, I was asked a standard question about all implementations of Singleton in java. And how bad they are.
And I was told that even static initialization is bad because of the likelihood of an uncontrolled exception in the constructor:
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
private Singleton() {
throw new RuntimeException("Wow... Exception in Singleton constructor...");
}
}
And they also told me that the Exception would be a "ClassNotFoundException", so it would be very difficult to find the problem in a real application.
I tried to get this exception:
public static void main(String[] args) {
new Thread(new Runnable(){
public void run() {
Singleton.getInstance();
}
}).start();
}
But all I get is an ExceptionInInitializerError ...
I searched for this exception everywhere I found it — they all spoke of the same problem that they told me in my interview. Nothing about "implementation" =)
Thank you for the attention.