org.ethelred.util.function.Lazy Maven / Gradle / Ivy
The newest version!
/* (C) 2024 */
package org.ethelred.util.function;
import java.util.*;
import java.util.function.*;
/**
* NOT THREAD SAFE - intended to be used in single request scope
*
* @param The type that will be created and supplied
*/
public class Lazy implements Supplier {
private final Supplier supplier;
private boolean got = false;
private boolean inGet = false;
private T value;
private Lazy(Supplier supplier) {
this.supplier = supplier;
}
public static Lazy lazy(Supplier supplier) {
return new Lazy<>(Objects.requireNonNull(supplier));
}
public static Lazy lazy(A argument, Function initializer) {
Objects.requireNonNull(initializer);
return new Lazy<>(() -> initializer.apply(argument));
}
public static Lazy lazy(Supplier argument, Function initializer) {
Objects.requireNonNull(argument);
Objects.requireNonNull(initializer);
return new Lazy<>(() -> initializer.apply(argument.get()));
}
public T get() {
if (inGet) {
throw new IllegalStateException("Cycle in Lazy.get()");
}
if (!got) {
got = true;
inGet = true;
value = supplier.get();
inGet = false;
}
return value;
}
}