All Downloads are FREE. Search and download functionalities are using the official Maven repository.

javax0.Lazy Maven / Gradle / Ivy

package javax0;

import java.util.function.Supplier;

public class Lazy implements Supplier {

    final private Supplier supplier;
    private boolean supplied = false;
    private T value;

    private Lazy(Supplier supplier) {
        this.supplier = supplier;
    }

    public static  Lazy let(Supplier supplier) {
        return new Lazy(supplier);
    }

    public static  Lazy.Sync sync(Supplier supplier) {
        return new Lazy<>(supplier).new Sync();
    }

    @Override
    public T get() {
        if (supplied) {
            return value;
        }
        supplied = true;
        return value = supplier.get();
    }

    public class Sync implements Supplier {

        private volatile boolean supplied = false;
        private volatile T value;

        /**
         * Gets a result.
         *
         * @return a result
         */
        @Override
        public T get() {
            if (supplied) {
                return value;
            }
            synchronized (this) {
                if (supplied) {
                    return value;
                }
                supplied = true;
                return value = (T) supplier.get();
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy