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

delight.async.flow.CallbackLatch Maven / Gradle / Ivy

Go to download

Asynchronous utilities for Java and GWT applications. Includes a simple promise implementation for Java.

There is a newer version: 0.1.5
Show newest version
/*******************************************************************************
 * Copyright 2011 Max Erik Rohde http://www.mxro.de
 * 
 * All rights reserved.
 ******************************************************************************/
package delight.async.flow;

import delight.async.Value;

/**
 * Allows to wait for a specified number of asynchronous operations.
 * 
 * @see {@link ListCallbackJoiner}
 * @author Max Erik Rohde
 * 
 *         Copyright Max Erik Rohde 2011. All rights reserved.
 */
public abstract class CallbackLatch {

	final int expected;
	Value received;
	volatile Value failed;

	
	/**
	 * This method is called when for all expected callbacks
	 * {@link #registerSuccess()} has been called.
	 */
	public abstract void onCompleted();

	public abstract void onFailed(Throwable t);

	/**
	 * Call this method when an expected callback has been received.
	 */
	public void registerSuccess() {
		synchronized (received) {
			synchronized (failed) {
				received.set(received.get() + 1);
				if (!failed.get() && received.get() == expected) {
					onCompleted();
				}
			}
		}
	}

	public void registerFail(final Throwable t) {
		synchronized (received) {
			synchronized (failed) {
				if (!failed.get()) {
					failed.set(true);
					onFailed(t);
				}
				failed.set(true);
			}
		}

	}

	public CallbackLatch(final int expected) {
		super();
		assert expected >= 0;

		this.expected = expected;
		this.failed = new Value(false);
		this.received = new Value(0);

		if (expected == 0) {
			onCompleted();
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy