package com.yahoo.yolean.concurrent;

import java.util.function.Supplier;

import static java.util.Objects.requireNonNull;

/**
 * Wraps a lazily initialised resource which needs to be shut down.
 * The wrapped supplier may not return {@code null}, and should be retryable on failure.
 * If it throws, it will be retried if {@link #get} is retried. A supplier that fails to
 * clean up partial state on failure may cause a resource leak.
 *
 * @author jonmv
 */
public class Memoized<T, E extends Exception> implements Supplier<T>, AutoCloseable {

    /** Provides a tighter bound on the thrown exception type. */
    @FunctionalInterface
    public interface Closer<T, E extends Exception> { void close(T t) throws E; }

    private final Object monitor = new Object();
    private final Closer<T, E> closer;
    private volatile T wrapped;
    private Supplier<T> factory;

    public Memoized(Supplier<T> factory, Closer<T, E> closer) {
        this.factory = requireNonNull(factory);
        this.closer = requireNonNull(closer);
    }

    public static <T extends AutoCloseable> Memoized<T, ?> of(Supplier<T> factory) {
        return new Memoized<>(factory, AutoCloseable::close);
    }

    @Override
    public T get() {
        // Double-checked locking: try the variable, and if not initialized, try to initialize it.
        if (wrapped == null) synchronized (monitor) {
            // Ensure the factory is called only once, by clearing it once successfully called.
            if (factory != null) wrapped = requireNonNull(factory.get());
            factory = null;

            // If we found the factory, we won the initialization race, and return normally; otherwise
            // if wrapped is non-null, we lost the race, wrapped was set by the winner, and we return; otherwise
            // we tried to initialise because wrapped was cleared by closing this, and we fail.
            if (wrapped == null) throw new IllegalStateException("already closed");
        }
        return wrapped;
    }

    @Override
    public void close() throws E {
        // Alter state only when synchronized with calls to get().
        synchronized (monitor) {
            // Ensure we only try to close the generated resource once, by clearing it after picking it up here.
            T maybe = wrapped;
            wrapped = null;
            // Clear the factory, to signal this has been closed.
            factory = null;
            if (maybe != null) closer.close(maybe);
        }
    }

}
@@ -31,16 +31,52 @@
 rrent;%0A%0A
+import java.util.function.Function;%0A
 import j
@@ -585,16 +585,23 @@
 %0A    /**
+%0A     *
  Provide
@@ -647,16 +647,21 @@
 on type.
+%0A    
  */%0A    
@@ -734,16 +734,25 @@
 ption%3E %7B
+%0A%0A       
  void cl
@@ -769,20 +769,26 @@
 hrows E;
+%0A%0A   
  %7D%0A%0A
+%0A
     priv
@@ -1244,32 +1244,295 @@
 :close);%0A    %7D%0A%0A
+    public static %3CT, U, E extends Exception, F extends E, G extends E%3E Memoized%3CU, E%3E combine(Memoized%3CT, F%3E inner, Function%3CT, U%3E outer, Closer%3CU, G%3E closer) %7B%0A        return new Memoized%3C%3E(() -%3E outer.apply(inner.get()), compose(closer, inner::close));%0A    %7D%0A%0A
     @Override%0A  
@@ -2823,9 +2823,758 @@
 %0A    %7D%0A%0A
+    private interface Thrower%3CE extends Exception%3E %7B void call() throws E; %7D%0A%0A    private static %3CT, E extends Exception, F extends E, G extends E%3E Closer%3CT, E%3E compose(Closer%3CT, G%3E inner, Thrower%3CF%3E outer) %7B%0A        return parent -%3E %7B%0A            Exception thrown = null;%0A            try %7B%0A                inner.close(parent);%0A            %7D%0A            catch (Exception e) %7B%0A                thrown = e;%0A            %7D%0A            try %7B%0A                outer.call();%0A            %7D%0A            catch (Exception e) %7B%0A                if (thrown != null) thrown.addSuppressed(e);%0A                else thrown = e;%0A            %7D%0A            @SuppressWarnings(%22unchecked%22)%0A            E e = (E) thrown;%0A            if (e != null) throw e;%0A        %7D;%0A    %7D%0A%0A
 %7D

Allow combining memoized objects