net.lenni0451.commons.Lazy Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of main Show documentation
Show all versions of main Show documentation
A java library with many useful functions and classes
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;
}
}