单例模式与线程安全(懒汉式、double check、volatile)

1.饿汉式单例

饿汉式单例:在类加载的时候,就已经初始化,无论之后用没用到。这样写法简单,线程安全,但是占内存。值得注意的是构造方法必须私有。

package Singleton;

public class HungerSingleton {
    private static  HungerSingleton singleton=new HungerSingleton();
    private HungerSingleton(){

    }
    public static HungerSingleton getInstance(){
        return singleton;
    }

    public static void main(String[]args){
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(HungerSingleton.getInstance());
                }
            }).start();
        }
    }
}
/*
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
Singleton.HungerSingleton@51d1628b
 */

 2.懒汉式单例

(1)比较简单的一种写法

与饿汉式单例不同的是,懒汉式单例是要在用到的时候才实例化,而且要考虑线程安全问题,多个线程在获取实例的时候需要对获取实例的方法加锁。如果不加锁,获取到的很可能不是同一个对象(当singleton未使用时(为null),多个线程获取实例时都判断singleton==null为真,都new了一个对象)。

package Singleton;

public class LazySingleton {
    private static LazySingleton singleton=null;
    private LazySingleton(){

    }
    public synchronized static LazySingleton getInstance(){
        if (singleton==null){
            singleton=new LazySingleton();
        }
        return singleton;
    }

    public static void main(String[]args){
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(LazySingleton.getInstance());
                }
            }).start();
        }
    }

}
/*
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
 */

(2)上述的写法是比较消耗性能的,如果单例已经实例化了,那么多个线程在获取实例时,只能有一个线程能获取到锁,调用getInstance()方法,其他线程会被阻塞在外边。

为了不让线程在方法外等待,而是实例不为空就直接返回,可以这么改写getInstance()方法:

package Singleton;

public class LazySingleton {
    private static LazySingleton singleton = null;

    private LazySingleton() {

    }

    public static LazySingleton getInstance() {
        if (singleton == null) {
            synchronized (LazySingleton.class) {
                singleton = new LazySingleton();
            }
        }
        return singleton;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(LazySingleton.getInstance());
                }
            }).start();
        }
    }

}
/*
Singleton.LazySingleton@1b094e2b
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
Singleton.LazySingleton@2a0170e1
 */

但是发现得到的并不是同一个对象,这是因为当一个线程进入synchronize中的代码块时,还没来得及实例化,另一个线程判断(singleton==null)进入if语句,但是没获取到锁,在外面等待,当前一个线程实例化完后,释放了锁,后一个线程拿到锁继续执行,又实例化了一个对象。所以这样写不是线程安全的。

(3)由于上面的原因,衍生出“双重检查”的写法:

package Singleton;

public class LazySingleton {
    private static LazySingleton singleton = null;

    private LazySingleton() {

    }

    public static LazySingleton getInstance() {
        if (singleton == null) {
            synchronized (LazySingleton.class) {
                if (singleton == null) {
                    singleton = new LazySingleton();
                }
            }
        }
        return singleton;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(LazySingleton.getInstance());
                }
            }).start();
        }
    }

}
/*
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
Singleton.LazySingleton@41ad0c3c
 */

按照逻辑,就算之后的线程进入了synchronize修饰的代码块,也要判断一下对象是否为空,从而避免了上面的问题。

(4)但是 在jvm中,new操作并不是原子性的,一个new语句包括了:

1.给instance分配空间

2.调用 Singleton 的构造函数来初始化

3.将instance对象指向分配的内存空间

在JVM中的及时编译存在指令重排序的优化,也就是说,上述执行顺序不能保证,如果第一个线程在实例化对象时,2执行在3前边,当线程执行完2,singleton就已经非空了,如果其他线程在第一个线程为执行完3之前,调用getInstance()方法将获取到一个不完整的对象(未初始化),使用则会报错。这个演示不了。。

所以需要volatile关键字修饰singeton,禁止JVM进行指令重排序。(这是最正确的写法,要记住)

package Singleton;

public class LazySingleton {
    private static volatile LazySingleton singleton = null;

    private LazySingleton() {

    }


    public static LazySingleton getInstance() {
        if (singleton == null) {
            synchronized (LazySingleton.class) {
                if (singleton == null) {
                    singleton = new LazySingleton();
                }
            }
        }
        return singleton;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(LazySingleton.getInstance());
                }
            }).start();
        }
    }

}
/*
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
Singleton.LazySingleton@1ec68e22
 */

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值