java单例模式

①饿汉式

public class Hungry {
    private Hungry(){}
    private static final Hungry HUNGRY = new Hungry();
    public static Hungry getInstance(){
        return HUNGRY;
    }

    public static void main(String[] args) {
        Hungry hungry = Hungry.getInstance();
        System.out.println(hungry);
    }
}

一上来就把对象new出来,并用static final修饰,通过getInstance方法返回该对象
这种方式缺点也很明显,不管用没用这个对象,都先new出来,浪费了内存

②懒汉式

public class Lazy {
    private Lazy(){
        System.out.println(Thread.currentThread().getName()+"调用了构造函数");
    }
    private static Lazy lazy;
    public static Lazy getInstance(){
        if(lazy == null){
            lazy = new Lazy();
        }
        return lazy;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                Lazy.getInstance();
            }).start();
        }
    }
}
Thread-0调用了构造函数
Thread-5调用了构造函数
Thread-3调用了构造函数
Thread-9调用了构造函数
Thread-1调用了构造函数
Thread-2调用了构造函数

这种方式相对于懒汉式有所改进,在类中只声明对象,不实例化;调用getInstance方法时,对象为null则实例化,否则直接返回。按理说只有第一次调用getInstance方法时会调用构造函数,new对象,以后都直接return。

单线程下确实没问题,但是多线程时,由运行结果可知,构造函数被多次调用,显然不符合单例模式。问题就出在多个线程同时调用了getInstance方法,解决方法就是通过synchronized加锁同步。

public class Lazy {
    private Lazy() {
        System.out.println(Thread.currentThread().getName() + "调用了构造函数");
    }

    private static Lazy lazy;

    public static Lazy getInstance() {
        if (lazy == null) {
            synchronized (Lazy.class) {
                if (lazy == null) {
                    lazy = new Lazy();
                }
            }
        }

        return lazy;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Lazy.getInstance();
            }).start();
        }
    }
}
Thread-0调用了构造函数

这时只有第一个线程调用了构造函数,符合预期的结果。

但是事实上还要考虑另一个问题:当new一个对象时,并不是一个原子操作,可以分为三个步骤:①为对象分配内存空间,②实例化对象,③向对象的引用指向该内存空间。正常情况下按照①②③顺序执行是没问题的,但是cpu可能会指令重排,执行顺序变为①③②,这时如果一个线程执行到③(即对象引用指向了内存空间,不为null,但是由于对象还没有实例化,这块内存什么都没有),另外一个线程同时调用了getInstance方法,判断lazy不为null,直接返回了lazy,就出问题了。解决方法就是使用volatile关键字禁止指令重排。

public class Lazy {
    private Lazy() {
        System.out.println(Thread.currentThread().getName() + "调用了构造函数");
    }

    private volatile static Lazy lazy;

    public static Lazy getInstance() {
        if (lazy == null) {
            synchronized (Lazy.class) {
                if (lazy == null) {
                    lazy = new Lazy();
                }
            }
        }

        return lazy;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Lazy.getInstance();
            }).start();
        }
    }
}

以上就是双重检测锁DCL

为什么要判断两次lazy == null
假设第一个线程进入同步块new对象的过程中,第二个线程同时调用了getInstance方法,因为对象还没有被实例化,外面的if不成立,所以也将会执行同步块中的代码,但是目前处于阻塞状态。等到第一个线程创建完对象,第二个线程进入同步块,就会判断里面的if不成立(第一个线程已经实例化了对象),就不会再new了,如果没有里面的if,第二个线程就会又new一个,单例模式就不成立了。

以上单例模式,由于java反射机制的存在,都是不安全的,如②懒汉式,可以通过如下反射破环单例模式:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Lazy {
    private Lazy() {
        System.out.println(Thread.currentThread().getName() + "调用了构造函数");
    }

    private volatile static Lazy lazy;

    public static Lazy getInstance() {
        if (lazy == null) {
            synchronized (Lazy.class) {
                if (lazy == null) {
                    lazy = new Lazy();
                }
            }
        }

        return lazy;
    }

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Lazy.getInstance();
        Constructor<Lazy> constructor = Lazy.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        constructor.newInstance();

    }
}
main调用了构造函数
main调用了构造函数

上述代码中,先通过getInstance方法正常创建对象,然后又通过反射newInstance创建对象。由运行结果可知,两次创建对象都调用了构造函数,因为反射通过setAccessible(true)破坏了构造函数的私有性,使得单例模式被破坏。

如果加一个字段验证呢?

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Lazy {
    private static boolean flag = false;
    private Lazy() {
        if(!flag){
            flag = true;
            System.out.println(Thread.currentThread().getName() + "调用了构造函数");
        }else{
            throw new RuntimeException("不要试图通过反射破坏单例!");
        }
       
    }

    private volatile static Lazy lazy;

    public static Lazy getInstance() {
        if (lazy == null) {
            synchronized (Lazy.class) {
                if (lazy == null) {
                    lazy = new Lazy();
                }
            }
        }

        return lazy;
    }

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Lazy.getInstance();
        Constructor<Lazy> constructor = Lazy.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        constructor.newInstance();

    }
}
main调用了构造函数
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at Lazy.main(Lazy.java:45)
Caused by: java.lang.RuntimeException: 不要试图通过反射破坏单例!
        at Lazy.<init>(Lazy.java:13)
        ... 5 more

这次加了一个flag字段,用在构造函数里,判断是否是第一次调用,第二次再调用时就会抛出异常,这样就无法通过反射无限制地创建对象了。

但是仍然是存在不安全性的,以上结论是在不知道这个字段的情况下实现的。所谓道高一尺,魔高一丈,如果这个验证字段被破解了,就可以通过反射重新设置它的值。

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Lazy {
    private static boolean flag = false;

    private Lazy() {
        if (!flag) {
            flag = true;
            System.out.println(Thread.currentThread().getName() + "调用了构造函数");
        } else {
            throw new RuntimeException("不要试图通过反射破坏单例!");
        }

    }

    private volatile static Lazy lazy;

    public static Lazy getInstance() {
        if (lazy == null) {
            synchronized (Lazy.class) {
                if (lazy == null) {
                    lazy = new Lazy();
                }
            }
        }

        return lazy;
    }

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
        // 正常创建第一个对象
        Lazy lazy1 = Lazy.getInstance();

        // 反射修改flag
        Field flag = Lazy.class.getDeclaredField("flag");
        flag.setAccessible(true);
        flag.set(lazy1, false);

        // 通过反射再次创建对象
        Constructor<Lazy> constructor = Lazy.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        constructor.newInstance();

    }
}
main调用了构造函数
main调用了构造函数

③静态内部类

public class External {
    private External(){}
    public static class Internal{
        private static final External EXTERNAL = new External();
    }
    public static External getInstance(){
        return Internal.EXTERNAL;
    }
}

将类的实例作为静态内部类的成员属性,再通过getInstance方法获得

④枚举

以上三种方法都存在不安全性,那么怎么才能保证安全呢,查看newInstance源码,直接就能看到这段代码:

if ((clazz.getModifiers() & Modifier.ENUM) != 0)
        throw new IllegalArgumentException("Cannot reflectively create enum objects");

不能通过反射创建枚举对象!
枚举类型其实是自带单例模式

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public enum EnumSingle {

    INSTANCE;

    public static EnumSingle getInstance() {
        return INSTANCE;
    }

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        EnumSingle instance1 = EnumSingle.getInstance();
        
        Constructor<EnumSingle> constructor = EnumSingle.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        EnumSingle instance2 = constructor.newInstance();

        System.out.println(instance1);
        System.out.println(instance2);

    }
}
Exception in thread "main" java.lang.NoSuchMethodException: EnumSingle.<init>()
        at java.lang.Class.getConstructor0(Class.java:3082)
        at java.lang.Class.getDeclaredConstructor(Class.java:2178)
        at EnumSingle.main(EnumSingle.java:17)

好像哪里不对?出错是必然的,但是错误信息应该是上面说的Cannot reflectively create enum objects,而不是这个。

NoSuchMethodException,没有该方法,显然是构造函数不对,通过反编译class文件,得知构造函数有两个参数,分别为Stringint

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public enum EnumSingle {

    INSTANCE;

    public static EnumSingle getInstance() {
        return INSTANCE;
    }

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        EnumSingle instance1 = EnumSingle.getInstance();

        Constructor<EnumSingle> constructor = EnumSingle.class.getDeclaredConstructor(String.class, int.class);
        constructor.setAccessible(true);
        EnumSingle instance2 = constructor.newInstance();

        System.out.println(instance1);
        System.out.println(instance2);

    }
}
Exception in thread "main" java.lang.IllegalArgumentException: Cannot reflectively create enum objects
        at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
        at EnumSingle.main(EnumSingle.java:19)

这才是想要的异常
得出结论:通过枚举实现的单例模式是安全的

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。