LazyCachedSupplier.java

/*
 * Copyright 2020 Collect Utils Authors
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
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;
}