作java开发的能够看看,Java单例模式的8种写法总结!

单例:Singleton,是指仅仅被实例化一次的类。设计模式

1、饿汉设计模式

public class SingletonHungry {
    private final static SingletonHungry INSTANCE = new SingletonHungry();

    private SingletonHungry() {
    }

    public static SingletonHungry getInstance() {
        return INSTANCE;
    }
}

由于单例对象一开始就初始化了,不会出现线程安全的问题。安全

PS:由于咱们只须要初始化1次,因此给INSTANCE加了final关键字,代表初始化1次后再也不容许初始化。多线程

2、简单懒汉设计模式

因为饿汉模式一开始就初始化好了,但若是一直没有被使用到的话,是会浪费珍贵的内存资源的,因此引出了懒汉模式。并发

懒汉:首次使用时才会去实例化对象。性能

public class SingletonLazy1 {
    private static SingletonLazy1 instance;

    private SingletonLazy1() {
    }

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

测试:测试

public class Main {
    public static void main(String[] args) {
        SingletonLazy1 instance1 = SingletonLazy1.getInstance();
        SingletonLazy1 instance2 = SingletonLazy1.getInstance();
        System.out.println(instance1);
        System.out.println(instance2);
    }
}

测试结果:从结果能够看出,打印出来的两个实例对象地址是同样的,因此认为是只建立了一个对象。
线程

3、进阶1:解决多线程并发问题

上述代码存在的问题:在多线程环境下,不能保证只建立一个实例,咱们进行问题的重现:设计

public class Main {
    public static void main(String[] args) {
        new Thread(()-> System.out.println(SingletonLazy1.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy1.getInstance())).start();
    }
}

结果:获取到的对象不同,这并非咱们的预期结果。3d

解决方案:指针

public class SingletonLazy2 {
    private static SingletonLazy2 instance;

    private SingletonLazy2() {
    }
    //在方法加synchronized修饰符
    public static synchronized SingletonLazy2 getInstance() {
        if (instance == null) {
            instance = new SingletonLazy2();
        }
        return instance;
    }
}

测试:

public class Main2 {
    public static void main(String[] args) {
        new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
    }
}

结果:多线程环境下获取到的是同个对象。

4、进阶2:缩小方法锁粒度

上一方案虽然解决了多线程问题,但因为synchronized关键字是加在方法上的,锁粒度很大,当有上万甚至更多的线程同时访问时,都被拦在了方法外,大大下降了程序性能,因此咱们要适当缩小锁粒度,控制锁的范围在代码块上。

public class SingletonLazy3 {
    private static SingletonLazy3 instance;

    private SingletonLazy3() {
    }

    public static SingletonLazy3 getInstance() {
        //代码块1:不要在if外加锁,否则和锁方法没什么区别
        if (instance == null) {
            //代码块2:加锁,将方法锁改成锁代码块
            synchronized (SingletonLazy3.class) {
                //代码块3
                instance = new SingletonLazy3();
            }
        }
        return instance;
    }
}

测试:

public class Main3 {
    public static void main(String[] args) {
        new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
    }
}

咱们看一下运行结果:仍是出现了线程安全的问题(每次执行均可能打印不一样的地址状况,只要证实是非线程安全的便可)。

缘由分析:当线程A拿到锁进入到代码块3而且尚未建立完实例时,线程B是有机会到达代码块2的,此时线程C和D可能在代码块1,当线程A执行完以后释放锁并返回对象1,线程B进入进入代码块3,又建立了新的对象2覆盖对象1并返回,最后当线程C和D在进行判null时发现instance非空,直接返回最后建立的对象2。

5、进阶3:双重检查锁DCL(Double-Checked-Locking)

所谓双重检查锁,就是在线程获取到锁以后再对实例进行第2次判空检查,判断是否是有上一个线程已经进行了实例化,有的话直接返回便可,不然进行实例初始化。

public class SingletonLazy4DCL {
    private static SingletonLazy4DCL instance;

    private SingletonLazy4DCL() {
    }

    public static SingletonLazy4DCL getInstance() {
        //代码块1:第一次判空检查
        if (instance == null) {
            //代码块2:加锁,将方法锁改成锁代码块
            synchronized (SingletonLazy3.class) {
                //代码块3:进行第二次(双重)判空检查
                if (instance == null) {
                    instance = new SingletonLazy4DCL();
                }
            }
        }
        return instance;
    }
}

测试:

public class Main4DCL {
    public static void main(String[] args) {
        new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
    }
}

6、进阶4:禁止指令重排

在对象的实例过程当中,大概可分为如下3个步骤:

  1. 分配对象内存空间
  2. 在空间中建立对象
  3. 实例指向分配到的内存空间地址

因为实例化对象的过程不是原子性的,且JVM自己对Java代码指令有重排的操做,可能1-2-3的操做被从新排序成了1-3-2,这样就会致使在3执行完以后还没来得及建立对象时,其余线程先读取到了未初始化的对象instance并提早返回,在使用的时候会出现NPE空指针异常。

解决:给instance加volatile关键字代表禁止指令重排,出现的几率不大, 但这是更安全的一种作法。

public class SingletonLazy5Volatile {
    //加volatile关键字
    private volatile static SingletonLazy5Volatile instance;

    private SingletonLazy5Volatile() {
    }

    public static SingletonLazy5Volatile getInstance() {
        //代码块1
        if (instance == null) {
            //代码块2:加锁,将方法锁改成锁代码块
            synchronized (SingletonLazy3.class) {
                //代码块3
                if (instance == null) {
                    instance = new SingletonLazy5Volatile();
                }
            }
        }
        return instance;
    }
}

7、进阶5:静态内部类

咱们还可使用静态类的静态变量被第一次访问时才会进行初始化的特性来进行懒加载初始化。把外部类的单例对象放到静态内部类的静态成员变量里进行初始化。

public class SingletonLazy6InnerStaticClass {
    private SingletonLazy6InnerStaticClass() {
    }

    public static SingletonLazy6InnerStaticClass getInstance() {
        return SingletonLazy6InnerStaticClass.InnerStaticClass.instance;
        //或者写成return InnerStaticClass.instance;
    }

    private static class InnerStaticClass {
        private static final SingletonLazy6InnerStaticClass instance = new SingletonLazy6InnerStaticClass();
    }
}

虽然静态内部类里的写法和饿汉模式很像,但它却不是在外部类加载时就初始化了,而是在第一次被访问到时才会进行初始化的操做(即getInstance方法被调用时),也就起到了懒加载的效果,而且它能够保证线程安全。

测试:

public class Main6InnerStatic {
    public static void main(String[] args) {
        new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
        new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
    }
}

反射攻击

虽然咱们一开始都对构造器进行了私有化处理,但Java自己的反射机制却仍是能够将private访问权限改成可访问,依旧能够建立出新的实例对象,这里以饿汉模式举例说明:

public class MainReflectAttack {
    public static void main(String[] args) {
        try {
            SingletonHungry normal1 = SingletonHungry.getInstance();
            SingletonHungry normal2 = SingletonHungry.getInstance();
            //开始反射建立实例
            Constructor<SingletonHungry> reflect = SingletonHungry.class.getDeclaredConstructor(null);
            reflect.setAccessible(true);
            SingletonHungry attack = reflect.newInstance();

            System.out.println("正常静态方法调用获取到的对象:");
            System.out.println(normal1);
            System.out.println(normal2);
            System.out.println("反射获取到的对象:");
            System.out.println(attack);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

8、枚举单例(推荐使用)

public enum SingletonEnum {
    INSTANCE;
}

枚举是最简洁、线程安全、不会被反射建立实例的单例实现,《Effective Java》中也代表了这种写法是最佳的单例实现模式。

单元素的枚举类型常常成为实现Singleton的最佳方法。 --《Effective Java》

为何说不会被反射建立对象呢?查阅构造器反射实例化对象方法newInstance的源码可知:反射禁止了枚举对象的实例化,也就防止了反射攻击,不用本身在构造器实现复杂的重复实例化逻辑了。

测试:

public class MainEnum {
    public static void main(String[] args) {
        SingletonEnum instance1 = SingletonEnum.INSTANCE;
        SingletonEnum instance2 = SingletonEnum.INSTANCE;
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }
}

总结:几种实现方式的优缺点

懒汉模式
  • 优势:节省内存。
  • 缺点:存在线程安全问题,若要保证线程安全,则写法复杂。
饿汉模式
  • 优势:线程安全。
  • 缺点:若是单例对象一直没被使用,则会浪费内存空间。
静态内部类
  • 优势:懒加载并避免了多线程问题,写法相比于懒汉模式更简单。
  • 缺点:须要多建立一个内部类。
枚举
  • 优势:简洁、天生线程安全、不可反射建立实例。
  • 缺点:暂无
相关文章
相关标签/搜索