-1

Where are the inner static classes are stored in new Java versions?

If static classes are stored in heap memory/ metaspace then how the below Singleton pattern implementation is thread safe?

public class BillPughSingleton {

    private BillPughSingleton(){}

    private static class SingletonHelper {
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance() {
        return SingletonHelper.INSTANCE;
    }
}

1 Answers1

3

It's thread-safe because the language mandates that it's thread-safe.

Assuming you call BillPughSingleton.getInstance(). The class BillPughSingleton must be initialized before getInstance is entered, but that's trivial.

getInstance() refers to the class SingletonHelper, so that needs to be initialized before execution can proceed. This requires the allocation of a BillPughSingleton (of which class has already been initialized) and the storing of a reference to that in INSTANCE. Now getInstance() can proceed.

Meanwhile, other threads that call getInstance() are waiting on an 'initialization lock' for the SingletonHelper class.

See JLS 12.4.2, Detailed Initialization Procedure.

This has nothing to do with 'where' anything is stored. It is a defined part of the semantics of a Java program.

Arfur Narf
  • 392
  • 1
  • 5