Reputation: 7940
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?
Upvotes: 1
Views: 2703
Reputation: 328619
You can't access the static members of a class (whether directly or through reflection) before it is loaded. And static final members are initialised during the loading process (step 9 of the JLS description).
So in your case there is no way a thread could:
INSTANCE
before it is properly constructed.INSTANCE
as null (unless the first call to new Foo()
throws an exception)Upvotes: 1
Reputation: 883
The best way to create a reflection-safe singleton is to use an enum. It is described here
Upvotes: 0