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;

public class Lazy implements AutoCloseable {
	private SupplierEx initializer;
	private ConsumerEx finalizer;
	private volatile T instance = null;

	public Lazy(SupplierEx initializer,
			ConsumerEx finalizer) {
		this.initializer = initializer;
		this.finalizer = finalizer;
	}

	public T get() throws E {
		if (instance == null) {
			synchronized (this) {
				if (instance == null) {
					instance = initializer.get();
				}
			}
		}
		return instance;
	}

	@Override
	public void close() {
		synchronized (this) {
			if (instance != null) {
				T instance_ = instance;
				instance = null;
				try {
					finalizer.accept(instance_);
				} catch (Exception e) {
					// Ignored
				}
			}
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy