/**
* 静态内部类,懒加载
* 本质上是利用类加载机制保证线程安全
* 只有在实际使用时才会触发类的初始化,也是懒加载的一种形式
*/
public class InnerClassSingleton {
//调用getInstance返回值时,才会导致静态内部类初始化
private static class InnerClassHolder{
private static InnerClassSingleton instance = new InnerClassSingleton();
}
private InnerClassSingleton(){
//反射攻击防护
if(InnerClassHolder.instance != null){
throw new RuntimeException("单例不允许多个实例");
}
}
public static InnerClassSingleton getInstance(){
return InnerClassHolder.instance;
}
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-23
  • 2022-12-23
  • 2021-05-18
猜你喜欢
  • 2021-10-17
  • 2022-12-23
  • 2022-03-06
  • 2021-08-21
  • 2022-12-23
  • 2022-12-23
  • 2021-05-20
相关资源
相似解决方案