public class EagerInitSingleton {
private static final EagerInitSingleton instance = new EagerInitSingleton();
//private constructor
private EagerInitSingleton(){}
public static EagerInitSingleton getInstance(){
return instance;
}
}
和静态块单例类代码如下 -
public class StaticBlockSingleton {
private static StaticBlockSingleton instance;
private StaticBlockSingleton(){}
//static block initialization for exception handling
static{
try{
instance = new StaticBlockSingleton();
}catch(Exception e){
throw new RuntimeException("Exception occured in singleton instance");
}
}
public static StaticBlockSingleton getInstance(){
return instance;
}
}
请不要谈论懒惰的初始化和线索安全。 我想弄清楚静态块单例中的两个静态块如何在这里产生差异。
答案 0 :(得分:1)
没有区别。
private static final EagerInitSingleton instance = new EagerInitSingleton();
相当于
private static final EagerInitSingleton instance;
static {
instance = new EagerInitSingleton();
}