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

net.lenni0451.commons.Lazy Maven / Gradle / Ivy

The newest version!
package net.lenni0451.commons;

import javax.annotation.concurrent.ThreadSafe;
import java.util.function.Supplier;

/**
 * An object to store a value that is only initialized when required.
* Useful for objects that are expensive to create and are not always needed. * * @param The type of the object */ @ThreadSafe public class Lazy { /** * Create a new lazy object. * * @param supplier The supplier to create the object * @param The type of the object * @return The lazy object */ public static Lazy of(final Supplier supplier) { return new Lazy<>(supplier); } private final Object lock = new Object(); private final Supplier supplier; private T value; private volatile boolean initialized = false; public Lazy(final Supplier supplier) { this.supplier = supplier; } /** * @return The value of the object */ public T get() { if (!this.initialized) { synchronized (this.lock) { if (!this.initialized) { this.value = this.supplier.get(); this.initialized = true; } } } return this.value; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy