java - 为什么在热切初始化中,在类加载时创建的单例类的实例可能会被认为是一个缺点?

标签 java singleton classloader

我知道静态变量是在运行时加载的,尽管我认为我理解这个问题,但我在下一个Eager Initialization Singelton实现中遇到了麻烦:

In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it.

public class EagerInitializedSingleton {

private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();

//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}

public static EagerInitializedSingleton getInstance(){
    return instance;
}

}

如果类的构造函数是私有(private)如何在类加载时创建类实例? 它只有一个 public 入口点,客户端必须显式调用该入口点,对吧?

最佳答案

Why in Eager initialization, the instance of the singleton class which created at the time of class loading could consider a drawback?

正如您引用的文字所说:

"... it has a drawback that [the] instance is created even though client application might not be using it."

为什么这是一个缺点?

因为:

  • 创建实例的计算成本可能很高(并且会增加启动时间)
  • 该实例可能会占用大量内存。

If the class's constructor is private, how the class instance can be created at the time of class loading?

它是在计算实例的初始化表达式时创建的。这种情况发生在 EagerInializedSingleton 类初始化时...这通常发生在类加载时。

表达式调用私有(private)构造函数。但这没关系,因为类中的代码可以看到自己的私有(private)字段/方法和构造函数。

Does it mean the class is getting loaded when the we call the getInstance method?

不一定。它可能会在那之前发生。但在那1之后就不会发生了。

1 - ...除非您已创建初始化依赖循环。

关于java - 为什么在热切初始化中,在类加载时创建的单例类的实例可能会被认为是一个缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38436303/

相关文章:

java - 将大的 2^63 十进制转换为二进制

design-patterns - 独特资源的单例替代方案

c# - WPF:关闭后无法重用窗口

python - 为什么这个单例实现是 "not thread safe"?

java - 使用自定义 ClassLoader 拦截 ClassLoader.getResource(String) 调用

java - 无法从 build.gradle 中排除模块

java - Artemis 使用 JMS 持久订阅多播地址

java - 如何检查服务器是否已启动超过 15 分钟?

java - 如何在WebSphere中创建共享库来共享jar文件

java - 即使项目是一个 jar,指定从类路径读取的路径的最佳方法是什么