When is a static nested class (and static members therein) loaded into memory?

前端 未结 2 1737
余生分开走
余生分开走 2021-02-14 01:40

Here, I was trying to implement a singleton class for my Database connectivity using the inner static helper class :

package com.myapp.modellayer;

public class         


        
相关标签:
2条回答
  • 2021-02-14 02:18

    The oracle doc page says:

    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

    You it is loaded the same way other classes are loaded.

    0 讨论(0)
  • 2021-02-14 02:22

    When the class gets loaded is just an implementation detail; you want to know when the class is initialized. It will get initialized only when it is first needed, and that is when you call getInstance().

    You are BTW using the lazy initialization holder class idiom which is based on exactly this guarantee by the Java Language Specification. As Josh Bloch said,

    This idiom is almost magical. There's synchronization going on, but it's invisible. The Java Runtime Environment does it for you, behind the scenes. And many VMs actually patch the code to eliminate the synchronization once it's no longer necessary, so this idiom is extremely fast.

    0 讨论(0)
提交回复
热议问题