我知道静态变量是在运行时加载的,尽管我认为我理解这个问题,但我在下一个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/