背景:写一个工具的时候遇到一个需要使用单例模式的场景,由于该实例消耗资源大且不一定会使用到,因此比较适合用懒汉模式实现。然后直接用的简单高效的静态内部类方式实现。
(关于单例模式的各种实现参考:设计模式之单例模式)
然后就遇到问题了,部分引入使用这个工具的应用一直出现 NoClassDefFoundError 报错,(error 异常,try-catch 的时候得 catch throwable)。再仔细看日志发现最前面有一个 ExceptionInInitializerError 异常。
查看日志及相关资料得知,在首次获取单例对象加载内部类时,会初始化类的静态属性,于是初始化单例对象时如果创建失败(构造方法抛出异常)就会导致内加载失败。并且由于类只会加载一次(加载失败了后面貌似也不会重新加载了),所以后面就一直抛异常,而且异常类型变为 NoClassDefFoundError。
复现代码如下:
public class Test{
public static void main(String[] args) {
// 重试三次获取单例
for (int j = 0; j < 3; j++) {
try {
// 获取单例,触发 Holder 内部类的类加载,并创建实例
A a = Holder.instance;
} catch (Throwable e) {
System.out.println("error: " + e.getClass().getSimpleName() + " msg:" + e.getMessage());
}
}
}
private static class Holder {
private static final A instance = new A();
}
private static int i=0;
public static class A {
public A() {
System.out.println("enter");
// 设置只有第一次创建失败,后面才能成功
if (i++<1) {
throw new RuntimeException("create A failed.");
}
System.out.println("success");
}
}
}
// 输出
// enter
// error: ExceptionInInitializerError msg:null
// error: NoClassDefFoundError msg:Could not initialize class Test$Holder
// error: NoClassDefFoundError msg:Could not initialize class Test$Holder
通过分析具体日志发现,初始化单例时的异常不可避免,且重试就能成功。于是改为双锁检测的懒汉模式。这样后续再次获取单例对象时就能重新初始化了。
public class Test {
public static void main(String[] args) {
for (int j = 0; j < 3; j++) {
try {
A a = getInstance();
} catch (Throwable e) {
System.out.println("error: " + e.getClass().getSimpleName() + " msg:" + e.getMessage());
}
}
}
private static volatile A instance;
public static A getInstance() {
if (instance == null) {
synchronized (A.class) {
if (instance == null) {
instance = new A();
}
}
}
return instance;
}
private static int i = 0;
public static class A {
public A() {
System.out.println("enter");
if (i++ < 1) {
throw new RuntimeException("create A failed.");
}
System.out.println("success");
}
}
}
// 输出
// enter
// error: RuntimeException msg:create A failed.
// enter
// success
因此,后续如果创建的单例对象如果不能保证完全不会出错的话,还是使用双锁检测的方式比较好。



