1

I thought that all static fields initialized in the order in which they appear in the source. However, then I saw the following code:

public static class Singleton {
    private static class InstanceHolder {
        public static Singleton instance = new Singleton(); //LINE X
    }

    private Singleton(){}

    public static Singleton getInstance() { 
        return InstanceHolder.instance;  
    }
}

Does it mean that field on LINE X is initialzed when getInstance method is called first time? Could anyone explain?

ThatsMe
  • 123
  • 4
  • 24
  • 1
    I added a better duplicate. the thing to remember is that in almost all situations a static class is just the same as a top-level class. So the same initialization rules apply. That is, it is initialized when loaded, and it is loaded when first referenced, which happens the first time the `getInstance()` method is called. – Mark Rotteveel Jul 03 '20 at 09:31
  • 1
    I added a better duplicate that answers your question. To quote the [top answer there](https://stackoverflow.com/a/24018148/466862) by Vladimir Kishlaly _"The JVM defers initializing the InstanceHolder class until it is actually used, and because the Singleton is initialized with a static initializer, no additional synchronization is needed. The first call to getInstance by any thread causes InstanceHolder to be loaded and initialized, at which time the initialization of the Singleton happens through the static initializer."_, which is basically what I posted in my comment. – Mark Rotteveel Jul 03 '20 at 09:43
  • That's not a static field. That's another class. – Thilo Jul 03 '20 at 10:26
  • @Thilo It is a static field, in a static class. – Mark Rotteveel Jul 03 '20 at 16:55
  • @MarkRotteveel Exactly. A static field in another class. Will get initialised when that class gets initialised. Not before. – Thilo Jul 04 '20 at 00:46

0 Answers0