单例模式

JAVA中正确使用的单例模式常用写法(6种写法)

星期六, 十一月 4th, 2017 | JAVA-and-J2EE | 没有评论

单例模式 老生常谈的一种模式,也是实际项目代码中比较常用的一种模式了.

文中做了6种方法,实际用的最多的也就 4.5两种,其实6是最完美的但是感觉别捏呢,不像个类,用的也并不多.

1.懒汉式,线程不安全

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

2.懒汉式,线程安全 (BUT.效率差)

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

3.双重检验锁

public static Singleton getSingleton() {
    if (instance == null) {                         //Single Checked
        synchronized (Singleton.class) {
            if (instance == null) {                 //Double Checked
                instance = new Singleton();       //非原子操作
            }
        }
    }
    return instance ;
}

问题:new Singleton非原子操作
1.给 instance 分配内存
2.调用Singleton 的构造函数来初始化成员变量
3.将instance对象指向分配的内存空间(执行完这步 instance 就为非 null 了)

解决办法 JDK1.5以前的版本会有问题, JDK1.5后用volatile关键字(立即可见及禁止指令重排序优化)来修饰变量.通过DCL(double checked locking)实现同步

public class Singleton {
    private volatile static Singleton instance; //这里为 volatile
    private Singleton (){}
    public static Singleton getSingleton() {
        if (instance == null) {                         
            synchronized (Singleton.class) {
                if (instance == null) {       
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }  
}

上面三种的写法基本上在项目中没有什么实用价值,下面的三种才是比较常用的

› Continue reading

Tags: ,

Search

文章分类

Links

Meta