/*
 * Licensed 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 org.jdbi.v3.core.internal;

import java.util.function.Consumer;
import java.util.function.Supplier;

// Thanks Holger!
// https://stackoverflow.com/questions/35331327/does-java-8-have-cached-support-for-suppliers

/**
 * Wraps a supplier and memoizes the object returned.
 *
 * @param <T> The type of the object returned by this supplier.
 * @see Supplier
 *
 */
public class MemoizingSupplier<T> implements Supplier<T> {
    private final Supplier<T> create;

    private Supplier<T> delegate = this::init;
    private boolean initialized;

    private MemoizingSupplier(Supplier<T> create) {
        this.create = create;
    }

    public static <T> MemoizingSupplier<T> of(Supplier<T> supplier) {
        return new MemoizingSupplier<>(supplier);
    }

    @Override
    public T get() {
        return delegate.get();
    }

    /**
     * Execute a method on the object returned from the supplier if the object was already created.
     * Skips execution if the underlying object was never created.
     *
     * @param consumer A consumer for the object returned by this supplier.
     */
    public void ifInitialized(Consumer<T> consumer) {
        if (initialized) {
            consumer.accept(get());
        }
    }

    private T init() { // NOPMD
        synchronized (this) {
            if (!initialized) {
                T result = create.get();
                initialized = true;
                delegate = () -> result;
            }
            return delegate.get();
        }
    }
}

@@ -1079,16 +1079,25 @@
 private 
+volatile 
 boolean 
@@ -1108,16 +1108,37 @@
 ialized;
+%0A    private T value;
 %0A%0A    pr
@@ -1416,24 +1416,83 @@
 t();%0A    %7D%0A%0A
+    private T internalGet() %7B%0A        return value;%0A    %7D%0A%0A
     /**%0A    
@@ -1905,17 +1905,8 @@
 () %7B
- // NOPMD
 %0A   
@@ -1984,16 +1984,13 @@
     
-T result
+value
  = c
@@ -2069,19 +2069,24 @@
 e = 
-() -%3E resul
+this::internalGe
 t;%0A 

Make the memoizer value inspectable