package editor.util;

import java.util.function.Supplier;

/**
 * This class "lazily" supplies a value by not evaluating it until the first time
 * it is requested.  Then that function's result is cached so it doesn't have to
 * be reevaluated again.
 *
 * @param <T> Type of object that is being lazily evaluated
 * @author Alec Roelke
 */
public class Lazy<T> implements Supplier<T>
{
    /** Whether or not the value has been computed yet. */
    private boolean flag;
    /** Reference to either the computed value or its generator (only one is needed at a time). */
    private Object ref;

    /**
     * Create a new Lazy supplier.
     *
     * @param val Function supplying the value to lazily evaluate.
     */
    public Lazy(Supplier<T> val)
    {
        flag = false;
        ref = val;
    }

    /**
     * If the value has not been computed, compute it and then return it.  Otherwise,
     * just return it.
     *
     * @return The value computed by the function
     */
    @Override
    @SuppressWarnings("unchecked")
    public T get()
    {
        if (!flag)
        {
            flag = true;
            ref = ((Supplier<T>)ref).get();
        }
        return (T)ref;
    }
}

@@ -15,16 +15,42 @@
 .util;%0A%0A
+import java.util.Objects;%0A
 import j
@@ -418,179 +418,180 @@
 /** 
-Whether or not the value has been computed yet. */%0A    private boolean flag;%0A    /** Reference to either the computed value or its generator (only one is needed at a time)
+Supplier of the value which will be called once when the value is first accessed. */%0A    private transient Supplier%3CT%3E supplier;%0A    /** The cached value of the computation
 . */
@@ -607,18 +607,15 @@
 ate 
-Object ref
+T value
 ;%0A%0A 
@@ -789,39 +789,46 @@
     
-flag = false;%0A        ref = 
+supplier = Objects.requireNonNull(
 val
+)
 ;%0A  
@@ -1036,161 +1036,277 @@
     
-@SuppressWarnings(%22unchecked%22)%0A    public T get()%0A    %7B%0A        if (!flag)%0A        %7B%0A            flag = true;%0A            ref = ((Supplier%3CT%3E)ref).get();
+public T get()%0A    %7B%0A        if (value == null)%0A        %7B%0A            synchronized (this)%0A            %7B%0A                if (value == null)%0A                %7B%0A                    value = supplier.get();%0A                    supplier = null;%0A                %7D%0A            %7D
 %0A   
@@ -1331,14 +1331,13 @@
 urn 
-(T)ref
+value
 ;%0A  

Make Lazy thread-/type-safe