Double-checked locking without volatile

前端 未结 5 1544
礼貌的吻别
礼貌的吻别 2020-12-24 03:06

I read this question about how to do Double-checked locking:

// Double-check idiom for lazy initialization of instance fields
private volatile FieldType fiel         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 03:51

    Using Enum or nested static class helper for lazy initialization otherwise just use static initialization if the initialization won't take much cost (space or time).

    public enum EnumSingleton {
        /**
         * using enum indeed avoid reflection intruding but also limit the ability of the instance;
         */
        INSTANCE;
    
        SingletonTypeEnum getType() {
            return SingletonTypeEnum.ENUM;
        }
    }
    
    /**
     * Singleton:
     * The JLS guarantees that a class is only loaded when it's used for the first time
     * (making the singleton initialization lazy)
     *
     * Thread-safe:
     * class loading is thread-safe (making the getInstance() method thread-safe as well)
     *
     */
    private static class SingletonHelper {
        private static final LazyInitializedSingleton INSTANCE = new LazyInitializedSingleton();
    }
    

    The "Double-Checked Locking is Broken" Declaration

    With this change, the Double-Checked Locking idiom can be made to work by declaring the helper field to be volatile. This does not work under JDK4 and earlier.

      class Foo {
            private volatile Helper helper = null;
            public Helper getHelper() {
                if (helper == null) {
                    synchronized(this) {
                        if (helper == null)
                            helper = new Helper();
                    }
                }
                return helper;
            }
        }
    

提交回复
热议问题