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
原创粉丝点击