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

org.macrocloud.kernel.toolkit.utils.Lazy Maven / Gradle / Ivy

There is a newer version: 1.1.0-RELEASE
Show newest version
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 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 s = supplier;
		if (s != null) {
			value = s.get();
			supplier = null;
		}
		return value;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy