1

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?

Lokesh
  • 7,810
  • 6
  • 48
  • 78

2 Answers2

1

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)
Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
0

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

Community
  • 1
  • 1
mmirwaldt
  • 843
  • 7
  • 17