LazyCachedSupplier.java

package net.morimekta.collect.util;

import java.util.function.Supplier;

import static java.util.Objects.requireNonNull;

/**
 * Simple lazily cached value supplier, also known as a 'memoized'
 * value supplier. This will lazily initialize the value on the first
 * 'get' call, and assumes the value supplier will return the same
 * value on every invocation, as the result should be thread-safe, but
 * *may* cause multiple calls to the value supplier.
 * <p>
 * Calling {@link #get()} will cause {@link NullPointerException} if the
 * memoized supplier returns {@code null}.
 * <p>
 * Calling {@link #get()} will on the first invocation cause the supplier
 * to be called in the same thread.
 *
 * @param <T> The memoized value type.
 */
public final class LazyCachedSupplier<T> implements Supplier<T> {
    /**
     * Make a lazily initialized supplier for the value
     * returned from the provided supplier.
     *
     * @param supplier The value supplier.
     * @param <M> The value type.
     * @return The lazy cached supplier.
     */
    public static <M> LazyCachedSupplier<M> lazyCache(Supplier<M> supplier) {
        return new LazyCachedSupplier<>(supplier);
    }

    /**
     * Make a lazily initialized supplier for the value
     * returned from the provided supplier.
     *
     * @param supplier The value supplier.
     */
    public LazyCachedSupplier(Supplier<T> supplier) {
        this.supplier = requireNonNull(supplier, "supplier == null");
    }

    /**
     * Reload the content of the cached value. This will always call the
     * origin supplier.
     *
     * @return The cached supplier.
     */
    public LazyCachedSupplier<T> reload() {
        synchronized (mutex) {
            // never reset from non-null to null.
            instance = requireNonNull(supplier.get(), "supplier.get() = null");
        }
        return this;
    }

    // ---- Supplier ----

    @Override
    public T get() {
        if (instance == null) {
            synchronized (mutex) {
                if (instance == null) {
                    instance = requireNonNull(supplier.get(), "supplier.get() = null");
                }
            }
        }
        return instance;
    }

    // ---- Private ----

    private transient volatile T instance = null;
    private transient final Object mutex = new Object();
    private final Supplier<T> supplier;
}