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

name.remal.gradle_plugins.toolkit.LazyInitializer Maven / Gradle / Ivy

There is a newer version: 0.64.11
Show newest version
package name.remal.gradle_plugins.toolkit;

import static javax.annotation.meta.When.UNKNOWN;

import com.google.errorprone.annotations.ForOverride;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import lombok.SneakyThrows;

public abstract class LazyInitializer {

    public static  LazyInitializer of(Supplier supplier) {
        return new LazyInitializer() {
            @Nonnull(when = UNKNOWN)
            @Override
            protected T create() {
                return supplier.get();
            }
        };
    }


    @Nonnull(when = UNKNOWN)
    @ForOverride
    protected abstract T create() throws Throwable;


    private static final Object NO_INIT = new Object();

    @Nonnull(when = UNKNOWN)
    @SuppressWarnings("unchecked")
    private volatile T object = (T) NO_INIT;

    @SneakyThrows
    @Nonnull(when = UNKNOWN)
    public final T get() {
        if (object == NO_INIT) {
            synchronized (this) {
                if (object == NO_INIT) {
                    object = create();
                }
            }
        }
        return object;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy