美文网首页
为什么大厂面试官喜欢问单例模式

为什么大厂面试官喜欢问单例模式

作者: TPEngineer | 来源:发表于2022-12-10 00:56 被阅读0次

    单例模式的五种实现看似丧心病狂,其实是一个由浅入深,再到化繁为简的过程。

    饿汉式

    饿汉式的实现思路是初始化的过程中就加载完成单例,而不是延迟再加载,有一种饥不择食的感觉,代码如下。

    import java.util.concurrent.atomic.AtomicLong;
    
    public class IdGen {
        private AtomicLong id = new AtomicLong(0);
        private static final IdGen instance = new IdGen();
    
        private IdGen() {
        }
    
        public static IdGen getInstance() {
            return instance;
        }
    
        public long getId() {
            var r = id.incrementAndGet();
            System.out.println(r);
            return r;
    
        }
    }
    

    这就适合一些业务加载时间长或者必须提前加载的使用场景。不少人觉得业务加载时间长应该延迟加载,这样才能加快启动速度。其实延迟加载会影响用户体验,因为延迟加载后,用户请求发过来,服务器还没加载完一直卡着响应,体验极差。

    注意看,Runtime类中的单例模式是用饿汉式实现的。

    /**
     * Every Java application has a single instance of class
     * <code>Runtime</code> that allows the application to interface with
     * the environment in which the application is running. The current
     * runtime can be obtained from the <code>getRuntime</code> method.
     * <p>
     * An application cannot create its own instance of this class.
     *
     * @author unascribed
     * @see java.lang.Runtime#getRuntime()
     * @since JDK1.0
     */
    public class Runtime {
        private static Runtime currentRuntime = new Runtime();
    
        public static Runtime getRuntime() {
            return currentRuntime;
        }
    
        /** Don't let anyone else instantiate this class */
        private Runtime() {
        }
    
        // ....
        public void addShutdownHook(Thread hook) {
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                sm.checkPermission(new RuntimePermission("shutdownHooks"));
            }
            ApplicationShutdownHooks.add(hook);
        }
        // ...
    }
    

    懒汉式

    最原始的懒汉式单例给方法加锁,实现延迟加载。但这种方法根本就不支持并发,是个串行操作。如果你用这种方法实现,一旦遇到并发的资源访问,系统根本hold不住,背锅概率99%。

    import java.util.concurrent.atomic.AtomicLong;
    
    public class IdGen {
        private AtomicLong id = new AtomicLong(0);
        private static IdGen instance;
    
        private IdGen() {
        }
    
        public static synchronized IdGen getInstance() {
            if (instance == null) {
                instance = new IdGen();
            }
            return instance;
        }
    
        public long getId() {
            var r = id.incrementAndGet();
            return r;
    
        }
    }
    

    双重检测

    双重检测既实现了延迟加载,又支持了并发。不少人可能会疑惑,为什么要检测两次instance==null,原因其实很简单,如果只检测一次,假设两个线程调用getInstance(),其中一个线程new出了单例,另一个线程等待第一个释放锁之后仍然可以new出单例,那这就破坏了单例模式,因此需要检测两次。

    有的人可能会说创建对象singleton = new Singleton()的底层是分为三个步骤:

    1. 为对象分配内存空间;
    2. 初始化对象;
    3. 对象地址的引用。

    因此要给 instance 成员变量加上 volatile 关键字,禁止指令重排序才行。实际上,只有很低版本的 Java 才会有这个问题。我们现在用的高版本的 Java 已经在 JDK 内部实现中解决了这个问题(解决的方法很简单,只要把对象 new 操作和初始化操作设计为原子操作,就自然能禁止重排序)。

    import java.util.concurrent.atomic.AtomicLong;
    
    public class IdGen {
        private AtomicLong id = new AtomicLong(0);
        private static IdGen instance;
    
        private IdGen() {
        }
    
        public static IdGen getInstance() {
            if (instance == null) {
                synchronized (IdGen.class) {
                    if (instance == null) {
                        instance = new IdGen();
                    }
                }
            }
            return instance;
        }
    
        public long getId() {
            var r = id.incrementAndGet();
            return r;
        }
    }
    

    内部静态类

    内部静态类的实现也实现了延迟加载,把并发的操作交给了JVM来处理,不过仍然有序列化和反射破坏单例模式的问题。

    import java.util.concurrent.atomic.AtomicLong;
    
    public class IdGen {
        private AtomicLong id = new AtomicLong(0);
    
        private IdGen() {
        }
    
        private static class SingletonHolder {
            private static final IdGen instance = new IdGen();
        }
    
        public static IdGen getInstance() {
            return SingletonHolder.instance;
        }
    
        public long getId() {
            var r = id.incrementAndGet();
            return r;
        }
    }
    

    枚举

    枚举也是实现了延迟加载,并发交由JVM处理,并且没有序列化和破坏单例模式的问题,可以说是延迟加载中的最优解。

    import java.util.concurrent.atomic.AtomicLong;
    
    // 测试类直接调用IdGen.INSTANCE
    public enum IdGen {
        INSTANCE;
    
        private AtomicLong id = new AtomicLong(0);
    
        public long getId() {
            var r = id.incrementAndGet();
            System.out.println(r);
            return r;
        }
    }
    

    总结

    综上,我们不难发现单例大体可以分为提前加载和延迟加载两大类,饿汉式单例在指定的应用场景是无可替代的,枚举实现的单例简洁安全,双重检测能考察你对锁的理解,因此单例面试题深得面试官喜爱。

    相关文章

      网友评论

          本文标题:为什么大厂面试官喜欢问单例模式

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