在这里,我试图使用内部静态助手类为我的数据库连接实现单例类:
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内存中:
解决方法
当类被加载时只是一个实现细节;你想知道什么时候初始化类.只有在第一次需要它时才会初始化它,也就是当你调用getInstance()时.
您使用的是lazy initialization holder class idiom,它完全基于Java语言规范的这种保证.正如Josh Bloch所说,
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.