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

de.thksystems.util.lang.Deferred Maven / Gradle / Ivy

Go to download

Commons for lang, crypto, xml, dom, text, csv, reflection, annotations, parsing, ...

There is a newer version: 4.3.3
Show newest version
/*
 * tksCommons
 *
 * Author  : Thomas Kuhlmann (ThK-Systems, http://www.thk-systems.de)
 * License : LGPL (https://www.gnu.org/licenses/lgpl.html)
 */
package de.thksystems.util.lang;

import java.util.Objects;
import java.util.function.Supplier;

/**
 * Lazy initialization using a {@link Supplier} (thread-safe).
 *
 * @see "Inspired by http://www.nosid.org/java8-threadsafe-lazy-initialization.html"
 */
public final class Deferred {
    private volatile Supplier resultSupplier;
    private T result = null;

    public Deferred(Supplier resultSupplier) {
        this.resultSupplier = Objects.requireNonNull(resultSupplier);
    }

    public T get() {
        if (resultSupplier != null) {
            synchronized (this) {
                if (resultSupplier != null) { // Double safety
                    result = resultSupplier.get();
                    resultSupplier = null;
                }
            }
        }
        return result;
    }

    public boolean isInitialized() {
        return resultSupplier == null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy