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

你。 提交于 2019-12-21 07:58:12

问题


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 DatabaseConnection {

    private DatabaseConnection() {
        //JDBC code...
    }

    private static class ConnectionHelper {
        // Instantiating the outer class
        private static final DatabaseConnection INSTANCE = new DatabaseConnection();
    }

    public static DatabaseConnection getInstance() {
        return ConnectionHelper.INSTANCE;
    }
}

However, my doubt is when does this static inner class, ConnectionHelper, gets loaded in to the JVM memory:

At time when DatabaseConnection class gets loaded, or At a time when getInstance() method is called ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/25192561/when-is-a-static-nested-class-and-static-members-therein-loaded-into-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!