You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@commons.apache.org by "Cheong Voon Leong (Jira)" <ji...@apache.org> on 2019/10/28 07:52:00 UTC

[jira] [Created] (LANG-1496) Lazily Initializing Singleton Object

Cheong Voon Leong created LANG-1496:
---------------------------------------

             Summary: Lazily Initializing Singleton Object
                 Key: LANG-1496
                 URL: https://issues.apache.org/jira/browse/LANG-1496
             Project: Commons Lang
          Issue Type: Improvement
            Reporter: Cheong Voon Leong


Java 8 functional interfaces are evaluated lazily. I think this is a better way to implement lazy initialization together with existing ConcurrentInitializer. Here is my proposed implementation.
{code:java|title=LazySingletonInitializer.java|borderStyle=solid}
public final class LazySingletonInitializer<T> implements ConcurrentInitializer<T> {

    private final Supplier<T> supplier;

    private final AtomicReference<T> ref;

    public LazySingletonInitializer(Supplier<T> supplier) {
        this.supplier = supplier;
        this.ref = new AtomicReference<>();
    }

    @Override
    public final T get() throws ConcurrentException {
        T result = ref.get();
        if (result == null) {
            synchronized (this) {
                result = ref.get();
                if (result == null) {
                    result = ref.updateAndGet((prev) -> (prev == null) ? supplier.get() : prev);
                }
            }
        }
        return result;
    }
}
{code}



--
This message was sent by Atlassian Jira
(v8.3.4#803005)