Java – when will static nested classes (and static members in them) be loaded into memory?

Here, I try to use the internal static helper class to implement the singleton class for my database connection:

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, I doubt when this static inner class connectionhelper is loaded into JVM memory:

When loading the databaseconnection class, or when calling the getInstance () method?

Solution

When the class is loaded, it is only an implementation detail; You want to know when to initialize the class It is initialized only when it is first needed, that is, when you call getInstance ()

You are using lazy initialization holder class idiom, which is completely based on the guarantee of the Java language specification As Josh Bloch said,

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>