Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement thread-safe lazy initialization?

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

// Not thread-safe public Foo getInstance(){     if(INSTANCE == null){         INSTANCE = new Foo();     }      return INSTANCE; } 
like image 544
mre Avatar asked Nov 28 '11 14:11

mre


1 Answers

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

Example:

ConcurrentInitializer<Foo> lazyInitializer = new LazyInitializer<Foo>() {          @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<Foo> fooSupplier = Suppliers.memoize(new Supplier<Foo>() {     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.

like image 180
Kenston Choi Avatar answered Sep 25 '22 10:09

Kenston Choi