美文网首页程序员Java设计模式
单例模式线程安全实验

单例模式线程安全实验

作者: 马拉松Mara | 来源:发表于2017-09-21 17:06 被阅读75次

    虽说单例模式属于设计模式中最简单的一个模式,但是如果深入探索一下,其实还是有些学问的。比如:

    • 如何设计一个线程安全的单例?
    • 如何设计一个多线程环境中耗时较低的单例?
      接下来,我将按照以下流程,用实验来验证单例模式的线程安全问题,以及多线程环境下,如何让对象实例创建时耗时更少。

    非线程安全的单例-懒汉式

    public class SingletonLazy {
    
        private static SingletonLazy singleton = null;
    
        private static int counter = 0;
    
        private SingletonLazy() {
            counter++;
            System.out.println(String.format("线程[%s]调用构造器,对象被创建[%d]次", Thread.currentThread().getName(), counter));
        }
    
        public static SingletonLazy getInstance() {
            if (singleton == null) {
                singleton = new SingletonLazy();
            }
            return singleton;
        }
    
    }
    

    那么,我们怎么知道它是否线程安全呢?
    接下来,我们使用Runnable,来创建10个线程,来观察构造器被调用了多少次。如果被调用了多次,自然创建了多个对象,就是线程不安全的:

    public class SingleTonApplication {
    
        /**
         * 简单的懒汉式在多线程环境下不是线程安全的。
         * @param args
         */
        public static void main(String[] args) {
            // 检测线程安全性
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    SingletonLazy singletonLazy = SingletonLazy.getInstance();
                    System.out.println(String.format("[%s]线程打印当前对象:%s", Thread.currentThread().getName(), singletonLazy.toString()));
                }
            };
            for (int i = 0; i < 10; i++) {
                Thread thread = new Thread(runnable);
                thread.start();
            }// end for
    
        }// end main
    }
    

    输出结果如下:

    线程[Thread-7]调用构造器,对象被创建[8]次
    线程[Thread-3]调用构造器,对象被创建[3]次
    线程[Thread-1]调用构造器,对象被创建[4]次
    线程[Thread-6]调用构造器,对象被创建[7]次
    线程[Thread-2]调用构造器,对象被创建[2]次
    线程[Thread-4]调用构造器,对象被创建[5]次
    线程[Thread-0]调用构造器,对象被创建[2]次
    线程[Thread-5]调用构造器,对象被创建[6]次
    线程[Thread-9]调用构造器,对象被创建[10]次
    [Thread-0]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@2116aeb
    线程[Thread-8]调用构造器,对象被创建[9]次
    [Thread-4]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@2eac0b4
    [Thread-2]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@1c2bd9d7
    [Thread-6]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@4bcf6203
    [Thread-1]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@475f7458
    [Thread-3]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@46d8dc2e
    [Thread-7]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@44fd2254
    [Thread-8]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@4268d15
    [Thread-5]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@45826b5c
    [Thread-9]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@755688aa

    可以看出,多个线程在竞争CPU资源时,创建了不止一个实例。
    通过这个实验,可以看出,这个单例不是线程安全的。
    于是,我们给getInstance方法加上synchronized关键字:

    public static synchronized SingletonLazy getInstance() {...}
    

    输出如下:

    线程[Thread-8]调用构造器,对象被创建[1]次
    [Thread-2]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@48c85a33
    [Thread-4]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@48c85a33
    [Thread-5]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@48c85a33
    [Thread-8]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@48c85a33
    [Thread-3]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@48c85a33
    [Thread-9]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@48c85a33
    [Thread-0]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@48c85a33
    [Thread-1]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@48c85a33
    [Thread-6]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@48c85a33
    [Thread-7]线程打印当前对象:com.hua.singleton.lazy.SingletonLazy@48c85a33
    Process finished with exit code 0

    可以看到线程[Thread-8]抢到了CPU资源,创建了唯一的实例。
    这时,线程安全的问题解决了。但是引发了一个新问题:
    当有多个线程几乎同时访问getInstance方法时,多个线程必须有次序地进入方法内,这样导致了若干个线程需要耗费等待进入临界区(被锁住的代码块)的时间。我们在getInstance方法添加sleep()来让进入临界区的线程等会儿,模拟对象在获取对象时的耗时,改造后的代码如下:

    线程安全的单例-懒汉式

    public class Singleton {
    
        private static Singleton singleton = null;
    
        private static int counter = 0;
    
        private Singleton() {
            counter++;
            System.out.println(String.format("构造对象被调用[%d]次", counter));
        }
    
        /**
         * 当有多个线程几乎同时访问getInstance方法时,多个线程必须有次序地进入方法内,
         * 这样导致了若干个线程需要耗费等待进入临界区(被锁住的代码块)的时间。
         * @return
         */
        public static synchronized Singleton getInstance() {
            // 模拟同步方法的耗时  start
            try {
                System.out.println(String.format("[%s]获取对象实例等待1秒", Thread.currentThread().getName()));
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 模拟同步方法的耗时  end
            if (singleton == null) {
                singleton = new Singleton();
            }
            return singleton;
        }
    
    }
    

    现在,我们需要借助CountDownLatch类,来让main主线程等待所有的子线程执行结束再结束,然后我们统计获取10次对象实例的耗时:

    public class SingleTonApplication {
    
        public static void main(String[] args) throws InterruptedException {
    
            int createTimes = 10;
    
            final CountDownLatch latch = new CountDownLatch(createTimes);
    
            // 检测线程安全性
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    Singleton singleton = Singleton.getInstance();
                    System.out.println(String.format("[%s]线程打印当前对象:%s", Thread.currentThread().getName(), singleton.toString()));
                    latch.countDown();
                }
            };
    
            long start = System.currentTimeMillis();
    
            for (int i = 0; i < createTimes; i++) {
                Thread thread = new Thread(runnable);
                thread.start();
            }// end for
    
            latch.await(); // 等待所有线程执行完
            System.out.println(String.format("获取对象[%d]次耗时:[%dms]", createTimes, (System.currentTimeMillis() - start)));
    
        }// end main
    }
    

    输出如下:

    [Thread-5]获取对象实例等待1秒
    构造对象被调用[1]次
    [Thread-9]获取对象实例等待1秒
    [Thread-5]线程打印当前对象:com.hua.singleton.lazythreadsafe.Singleton@b07848
    [Thread-8]获取对象实例等待1秒
    [Thread-9]线程打印当前对象:com.hua.singleton.lazythreadsafe.Singleton@b07848
    [Thread-7]获取对象实例等待1秒
    [Thread-8]线程打印当前对象:com.hua.singleton.lazythreadsafe.Singleton@b07848
    [Thread-6]获取对象实例等待1秒
    [Thread-7]线程打印当前对象:com.hua.singleton.lazythreadsafe.Singleton@b07848
    [Thread-1]获取对象实例等待1秒
    [Thread-6]线程打印当前对象:com.hua.singleton.lazythreadsafe.Singleton@b07848
    [Thread-2]获取对象实例等待1秒
    [Thread-1]线程打印当前对象:com.hua.singleton.lazythreadsafe.Singleton@b07848
    [Thread-4]获取对象实例等待1秒
    [Thread-2]线程打印当前对象:com.hua.singleton.lazythreadsafe.Singleton@b07848
    [Thread-3]获取对象实例等待1秒
    [Thread-4]线程打印当前对象:com.hua.singleton.lazythreadsafe.Singleton@b07848
    [Thread-0]获取对象实例等待1秒
    [Thread-3]线程打印当前对象:com.hua.singleton.lazythreadsafe.Singleton@b07848
    [Thread-0]线程打印当前对象:com.hua.singleton.lazythreadsafe.Singleton@b07848
    获取对象[10]次耗时:[10052ms]

    根据输出日志,我们看到,每个线程在获取实例时,都需要等待一定的时间。多线程的优势并没有发挥出来,其实,我们只需要在创建对象时,进行同步。所以,引入双重校验锁的单例创建模式。

    线程安全、耗时更少的单例-双重校验锁

    public class SingletonDCL {
    
        private volatile static SingletonDCL singleton;
    
        private static int counter = 0;
    
        private SingletonDCL() {
            counter++;
            System.out.println(String.format("构造对象被调用[%d]次", counter));
        }
    
        /**
         * 双重校验锁式(也有人把双重校验锁式和懒汉式归为一类)分别在代码锁前后进行判空校验,
         * 避免了多个有机会进入临界区的线程都创建对象,
         * 同时也避免了后来线程在"lazythreadsafe"中,先来线程创建对象后,但仍未退出临界区的情况下等待
         * @return
         */
        public static SingletonDCL getInstance() {
            // 模拟同步方法的耗时  start
            try {
                System.out.println(String.format("[%s]获取对象实例等待1秒", Thread.currentThread().getName()));
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 模拟同步方法的耗时  end
            if (singleton == null) {
                synchronized (Singleton.class) {
                    if (singleton == null) {
                        singleton = new SingletonDCL();
                    }// end if
                }// end syn
            }// end if
            return singleton;
        }
    
    }
    

    实验代码:

    public class SingleTonApplication {
    
        public static void main(String[] args) throws InterruptedException {
            int createTimes = 10;
            final CountDownLatch latch = new CountDownLatch(createTimes);
    
            // 检测线程安全性
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    SingletonDCL singleton = SingletonDCL.getInstance();
                    System.out.println(String.format("[%s]线程打印当前对象:%s", Thread.currentThread().getName(), singleton.toString()));
                    latch.countDown(); // 将count值减1
                }
            };
    
            long start = System.currentTimeMillis();
    
            for (int i = 0; i < createTimes; i++) {
                Thread thread = new Thread(runnable);
                thread.start();
            }// end for
    
            // 等待所有线程完成工作
            latch.await();
            System.out.println(String.format("获取对象[%d]次耗时:[%dms]", createTimes, (System.currentTimeMillis() - start)));
    
        }// end main
    }
    
    

    控制台输出为:

    [Thread-9]获取对象实例等待1秒
    [Thread-6]获取对象实例等待1秒
    [Thread-1]获取对象实例等待1秒
    [Thread-7]获取对象实例等待1秒
    [Thread-2]获取对象实例等待1秒
    [Thread-3]获取对象实例等待1秒
    [Thread-5]获取对象实例等待1秒
    [Thread-8]获取对象实例等待1秒
    [Thread-0]获取对象实例等待1秒
    [Thread-4]获取对象实例等待1秒
    构造对象被调用[1]次
    [Thread-1]线程打印当前对象:com.hua.singleton.dcl.SingletonDCL@7115e166
    [Thread-2]线程打印当前对象:com.hua.singleton.dcl.SingletonDCL@7115e166
    [Thread-3]线程打印当前对象:com.hua.singleton.dcl.SingletonDCL@7115e166
    [Thread-6]线程打印当前对象:com.hua.singleton.dcl.SingletonDCL@7115e166
    [Thread-9]线程打印当前对象:com.hua.singleton.dcl.SingletonDCL@7115e166
    [Thread-8]线程打印当前对象:com.hua.singleton.dcl.SingletonDCL@7115e166
    [Thread-5]线程打印当前对象:com.hua.singleton.dcl.SingletonDCL@7115e166
    [Thread-7]线程打印当前对象:com.hua.singleton.dcl.SingletonDCL@7115e166
    [Thread-0]线程打印当前对象:com.hua.singleton.dcl.SingletonDCL@7115e166
    [Thread-4]线程打印当前对象:com.hua.singleton.dcl.SingletonDCL@7115e166
    获取对象[10]次耗时:[1031ms]

    我们可以看到,在等待时,多个线程同时进入了getInstance方法。
    随后,先检查一次singleton有没有被创建,如果被创建了,就直接返回。如果没有被创建,进入同步代码块。
    在同步代码块中,再判断一次有没有singleton对象,如果有就不做处理。没有时,才创建。
    这时,可能有朋友问,为何同步代码块里面也要判断if (singleton == null)呢?我们可以想象一下,多个线程同时走到getInstance方法中,这时同步代码块里,singleton还没有被创建,如果不判断,程序会认为此处应该创建实例,这样就会有多个实例被创建。我们的单例模式自然就不起作用了。

    总结

    双重校验锁式的单例模式线程安全,同时避免了后来线程在先来线程创建对象后,但仍未退出临界区的情况下的等待。

    相关文章

      网友评论

        本文标题:单例模式线程安全实验

        本文链接:https://www.haomeiwen.com/subject/cyqtextx.html