Spring面试题

由 Geooo 发布于 February 24, 2022
  1. 有用过单例模式吗?Singleton的有几种实现方式?
    • 1) 饿汉式:在类加载阶段就把这个单例的对象new出来,不需要考虑线程安全问题,但浪费内存,不需要用上这个对象的时候也需要分配内存。
    • 2) 懒汉式:在有需要到这个单例对象的时候才把对象new出来,但是此时需要考虑线程安全的问题,因此需要用 双重校验锁 进行验证
    • 3) 静态内部类:这种方法使用了类加载机制来保证只创建一个 instance,但是内部类不会在JVM启动的时候类加载,而是等到这个方法调到的时候才会进行类加载,该方法实现了懒汉式和线程安全。
    • 4) 枚举

饿汉式

1
2
3
4
5
6
7
8
9
10
11
public class Singleton {     

    private static Singleton instance = new Singleton();

    private Singleton() {};

    public static Singleton getInstance() {
        return instance;
    }

}

懒汉式(双重校验锁方法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Singleton {
    private static volatile Singleton instance = null;

    private Singleton() {};

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

}

内部类实现方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Singleton {
    private static class SingleHandler {
        private static Singleton instance = new Singleton();
    }   

    private Singleton() {};

    public static Singleton getInstance() {
        return SingleHandler.instance;
    }

}

枚举

1
2
3
4
5
6
public enum Singleton{
    instance;
    public void method() {};
}