org.macrocloud.kernel.toolkit.utils.Lazy Maven / Gradle / Ivy
package org.macrocloud.kernel.toolkit.utils;
import org.springframework.lang.Nullable;
import java.io.Serializable;
import java.util.function.Supplier;
/**
* Holder of a value that is computed lazy.
*
* @author macro
* @param the generic type
*/
public class Lazy implements Supplier, Serializable {
/** The supplier. */
@Nullable
private transient volatile Supplier extends T> supplier;
/** The value. */
@Nullable
private T value;
/**
* Creates new instance of Lazy.
*
* @param 泛型标记
* @param supplier Supplier
* @return Lazy
*/
public static Lazy of(final Supplier supplier) {
return new Lazy<>(supplier);
}
/**
* Instantiates a new lazy.
*
* @param supplier the supplier
*/
private Lazy(final Supplier supplier) {
this.supplier = supplier;
}
/**
* Returns the value. Value will be computed on first call.
*
* @return lazy value
*/
@Nullable
@Override
public T get() {
return (supplier == null) ? value : computeValue();
}
/**
* Compute value.
*
* @return the t
*/
@Nullable
private synchronized T computeValue() {
final Supplier extends T> s = supplier;
if (s != null) {
value = s.get();
supplier = null;
}
return value;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy