Lokesh
Lokesh

Reputation: 7940

Singleton: Throwing exception in constructor

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

Answers (2)

assylias
assylias

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:

  • see INSTANCE before it is properly constructed.
  • see INSTANCE as null (unless the first call to new Foo() throws an exception)
  • initialise a second instance (unless that code relies on a different class loader)

Upvotes: 1

mmirwaldt
mmirwaldt

Reputation: 883

The best way to create a reflection-safe singleton is to use an enum. It is described here

Upvotes: 0

Related Questions