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

me.qoomon.gitversioning.commons.Lazy Maven / Gradle / Ivy

There is a newer version: 9.10.0
Show newest version
package me.qoomon.gitversioning.commons;

import java.util.concurrent.Callable;
import java.util.function.Supplier;

import static java.util.Objects.requireNonNull;

public final class Lazy implements Supplier {

    private volatile Callable initializer;
    private T value;

    public Lazy(Callable initializer) {
        this.initializer = requireNonNull(initializer);
    }

    public T get() {
        if (initializer != null) {
            synchronized (this) {
                if (initializer != null) {
                    try {
                        value = initializer.call();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    initializer = null;
                }
            }
        }
        return value;
    }

    public static  Lazy of(T value) {
        return new Lazy<>(() -> value);
    }

    public static  Lazy by(Callable supplier) {
        return new Lazy<>(supplier);
    }

    public static  V get(Lazy value) {
        if (value != null) {
            return value.get();
        }
        return null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy