In order to prevent Singleton from being broken by using reflection one way is to throw an exception in private constructor as shown in code below:
public final class Foo {
private static final Foo INSTANCE = new Foo();
private Foo() {
if (INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return INSTANCE;
}
}
Above is a standard code but what i am thinking is that is it thread safe? If multiple threads try to create the instance using reflection at same time [i.e. before the class is loaded in main memory which implies instance will be null ] then will they succeed?