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

com.xqbase.util.Lazy Maven / Gradle / Ivy

There is a newer version: 0.2.18
Show newest version
package com.xqbase.util;

import com.xqbase.util.function.ConsumerEx;
import com.xqbase.util.function.SupplierEx;

/**
 * A lazy factory for singletons implemented by double-checked locking.
 *
 * @param  type of the instance
 * @param  type of exception when initializing
 */
public class Lazy implements AutoCloseable {
	private SupplierEx initializer;
	private ConsumerEx finalizer;
	private volatile T object = null;

	/**
	 * Create a lazy factory by the given initializer and finalizer.
	 *
	 * @param initializer a supplier to create the instance
	 * @param finalizer a consumer to destroy the instance
	 */
	public Lazy(SupplierEx initializer,
			ConsumerEx finalizer) {
		this.initializer = initializer;
		this.finalizer = finalizer;
	}

	/**
	 * Create or get the instance.
	 *
	 * @return the instance
	 * @throws E exception thrown by initializer
	 */
	public T get() throws E {
		// use a temporary variable to reduce the number of reads of the volatile field
		// see commons-lang3
		T result = object;
		if (object == null) {
			synchronized (this) {
				result = object;
				if (object == null) {
					object = result = initializer.get();
				}
			}
		}
		return result;
	}

	/**
	 * Close the lazy factory and destroy the instance if created.
	 */
	@Override
	public void close() {
		synchronized (this) {
			if (object != null) {
				T object_ = object;
				object = null;
				try {
					finalizer.accept(object_);
				} catch (Exception e) {
					// Ignored
				}
			}
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy