做java开发的可以看看,Java单例模式的8种写法总结!

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

一、饿汉设计模式

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

    private SingletonHungry() {
    }

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

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

PS:因为我们只需要初始化1次,所以给INSTANCE加了final关键字,表明初始化1次后不再允许初始化。

二、简单懒汉设计模式

由于饿汉模式一开始就初始化好了,但如果一直没有被使用到的话,是会浪费珍贵的内存资源的,所以引出了懒汉模式。

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

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);
    }
}

测试结果:从结果可以看出,打印出来的两个实例对象地址是一样的,所以认为是只创建了一个对象。

三、进阶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();
    }
}

结果:获取到的对象不一样,这并不是我们的预期结果。

解决方案:

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();
    }
}

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

四、进阶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。

五、进阶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();
    }
}

六、进阶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;
    }
}

七、进阶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();
        }
    }
}

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

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());
    }
}

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

懒汉模式
  • 优点:节省内存。
  • 缺点:存在线程安全问题,若要保证线程安全,则写法复杂。
饿汉模式
  • 优点:线程安全。
  • 缺点:如果单例对象一直没被使用,则会浪费内存空间。
静态内部类
  • 优点:懒加载并避免了多线程问题,写法相比于懒汉模式更简单。
  • 缺点:需要多创建一个内部类。
枚举
  • 优点:简洁、天生线程安全、不可反射创建实例。
  • 缺点:暂无
原文地址:https://www.cnblogs.com/lwh1019/p/14297561.html