本文介绍了何时将静态嵌套类(以及其中的静态成员)加载到内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我尝试使用内部静态助手类为我的数据库连接实现单例类:

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;
    }
}

然而,我怀疑这个静态内部类是什么时候, ConnectionHelper ,被加载到JVM内存中:

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

加载 DatabaseConnection 类时,或
在调用 getInstance() 方法的时候?

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

推荐答案

当类加载只是一个实现细节;你想知道什么时候初始化。它只会在第一次需要时才会被初始化,那就是你打电话给 getInstance()

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().

你使用基于的BTW完全由Java语言规范保证。正如Josh Bloch所说,

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,

这篇关于何时将静态嵌套类(以及其中的静态成员)加载到内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 01:10