How to implement thread-safe lazy initialization?

后端 未结 12 814
一整个雨季
一整个雨季 2020-11-28 04:13

What are some recommended approaches to achieving thread-safe lazy initialization? For instance,

// Not thread-safe
public Foo getI         


        
12条回答
  •  旧巷少年郎
    2020-11-28 04:39

    With Java 8 we can achieve lazy initialization with thread safety. If we have Holder class and it needs some heavy resources then we can lazy load the heavy resource like this.

    public class Holder {
        private Supplier heavy = () -> createAndCacheHeavy();
    
        private synchronized Heavy createAndCacheHeavy() {
    
            class HeavyFactory implements Supplier {
                private final Heavy heavyInstance = new Heavy();
    
                @Override
                public Heavy get() {
                    return heavyInstance;
                }
            }
            if (!HeavyFactory.class.isInstance(heavy)) {
                heavy = new HeavyFactory();
            }
            return heavy.get();
        }
    
        public Heavy getHeavy() {
            return heavy.get();
        }
    }
    
    public class Heavy {
        public Heavy() {
            System.out.println("creating heavy");
        }
    }
    

提交回复
热议问题