How to implement thread-safe lazy initialization?

后端 未结 12 828
一整个雨季
一整个雨季 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:52

    If you're using Apache Commons Lang, then you can use one of the variations of ConcurrentInitializer like LazyInitializer.

    Example:

    ConcurrentInitializer lazyInitializer = new LazyInitializer() {
    
            @Override
            protected Foo initialize() throws ConcurrentException {
                return new Foo();
            }
        };
    

    You can now safely get Foo (gets initialized only once):

    Foo instance = lazyInitializer.get();
    

    If you're using Google's Guava:

    Supplier fooSupplier = Suppliers.memoize(new Supplier() {
        public Foo get() {
            return new Foo();
        }
    });
    

    Then call it by Foo f = fooSupplier.get();

    From Suppliers.memoize javadoc:

    Returns a supplier which caches the instance retrieved during the first call to get() and returns that value on subsequent calls to get(). The returned supplier is thread-safe. The delegate's get() method will be invoked at most once. If delegate is an instance created by an earlier call to memoize, it is returned directly.

提交回复
热议问题