懒汉模式-线程不安全


public class Singleton {
private static Singleton instance;
private Singleton (){ } public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

懒汉模式-线程安全


public class Singleton {
private static Singleton instance;
private Singleton (){ } public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

饿汉模式


public class Singleton {
private static Singleton instance = new Singleton(); private Singleton (){ } public static Singleton getInstance() {
return instance;
}
}

饿汉模式-变种


public class Singleton {
private static Singleton instance = null; static {
instance = new Singleton();
} private Singleton() { } public static Singleton getInstance() {
return instance;
}
}

静态内部类


public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
} private Singleton (){ } public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}

双重校验锁


public class Singleton {
private volatile static Singleton singleton;
private Singleton (){ }
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}

枚举


public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}

最新文章

  1. tornado 学习笔记9 Tornado web 框架---模板(template)功能分析
  2. ionic 界面数据缓存问题
  3. (转载)在Visual Studio 2015中使用Git
  4. Android WebView 开发教程
  5. asp.Net获取脚本传过来的参数的方法汇总
  6. js实现时钟
  7. stage simulator
  8. MongoDB 基础命令使用学习记录
  9. java 21-13 合并
  10. 微信新版支持读取iPhone M7/M8协处理器运动数据 与好友PK一下运动量吧
  11. zoj 1097 普吕弗序列
  12. Shell实现跳板机,为什么用跳板机
  13. .NET中如何使用反序列化JSON字符串/序列化泛型对象toJsonStr
  14. Python之路【第一篇】:Python前世今生
  15. bootstrap's plugin:sthe usage of carousel
  16. python+selenium自动化软件测试(第1章):环境搭建,你也可以直接用Anaconda!
  17. 推荐一款接口文档在线管理系统-MinDoc
  18. Git环境配置+VSCode中文乱码问题
  19. springmvc+mybatis+mysql 数据库插入中文是乱码
  20. MongoDB 分片集群技术

热门文章

  1. 23.Python位运算符详解
  2. 给string定义一个扩展方法
  3. 在已开启Chrome窗口上调试
  4. [Java]手动构建表达式二叉树,求值,求后序表达式
  5. Node fs 创建多层文件夹
  6. Redis集群配置和常见异常解决
  7. linux常用命令(16)locate命令
  8. k8s开启cadvisor http 服务
  9. 非线性函数图像表示(GLSL)
  10. Hibernate不同数据库的连接及SQL方言