java中Singleton的几种实现方式
来源:互联网 发布:淘宝过户需要多久 编辑:程序博客网 时间:2024/06/06 13:18
1. 静态、线程安全和双锁校验实现方式
class Singleton { private volatile static Singleton _instance; private Singleton() { // preventing Singleton object instantiation from outside } /**
* 静态类实现
* 1st version: creates multiple instance if two thread access * this method simultaneously */ public static Singleton getInstance() { if (_instance == null) { _instance = new Singleton(); } return _instance; } /**
* 线程安全 * 2nd version : this definitely thread-safe and only * creates one instance of Singleton on concurrent environment * but unnecessarily expensive due to cost of synchronization * at every call. */ public static synchronized Singleton getInstanceTS() { if (_instance == null) { _instance = new Singleton(); } return _instance; } /**
* 双锁校验 * 3rd version : An implementation of double checked locking of Singleton. * Intention is to minimize cost of synchronization and improve performance, * by only locking critical section of code, the code which creates instance of Singleton class. * By the way this is still broken, if we don't make _instance volatile, as another thread can * see a half initialized instance of Singleton. */ public static Singleton getInstanceDC() { if (_instance == null) { synchronized (Singleton.class) { if (_instance == null) { _instance = new Singleton(); } } } return _instance; }}
2. Enum实现方式(推荐)
/**
* Singleton pattern example using Java Enumj
*/public enum EasySingleton{
INSTANCE;
}
0 0
- java中singleton的几种实现方式
- java中Singleton的几种实现方式
- Singleton模式的几种实现方式
- singleton模式的几种实现方式
- 几种Singleton模式的java实现
- 单例模式singleton的几种实现方式
- java Singleton 几种方式解析
- java Singleton 几种方式解析
- java Singleton 几种方式解析
- Singleton的几种实现
- Singleton Pattern 的几种方式
- Singleton Pattern 的几种方式
- java实现单例singleton的几种模式
- java中弹出式对话框的几种实现方式
- java中线程池的几种实现方式
- java中线程池的几种实现方式
- Java中阻塞队列的几种实现方式
- java中实现swap函数的几种方式
- unique函数去除重复元素在vector中的应用
- Win7/win8 系统下 Firefox hostadmin插件无法修改Host
- 【翻译】D3D10/D3D11中的纹理资源
- 多校3
- KMP算法小结
- java中Singleton的几种实现方式
- 中文信息摘要
- 中国大学MOOC-翁恺-C语言程序设计习题集 05-0 到 06-3
- 【随行日志】与网络有关-?的含义
- hdoj 1896 Stones [STL 优先队列]
- socket基础总结
- 无聊写排序之 ----部分排序(Partial Sort)
- 单例模式(Singleton)
- VS中运行后控制台窗口一闪就没了