package org.implab.gradle.common.utils;

import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

public class LazyValue<T> implements Supplier<T> {
    private final AtomicReference<T> reference = new AtomicReference<>();

    private final Supplier<T> innerSupplier;

    public LazyValue(Supplier<T> supplier) {
        this.innerSupplier = supplier;
    }

    @Override
    public T get() {
        var t = reference.get();
        if (t != null)
            return t;
        return updateValue();
    }

    private T updateValue() {
        var v = innerSupplier.get();
        var t = reference.compareAndExchange(null, v);
        return t != null ? t : v;
    }

}
