com.firefly.utils.concurrent.Callback Maven / Gradle / Ivy
package com.firefly.utils.concurrent;
/**
*
* A callback abstraction that handles completed/failed events of asynchronous
* operations.
*
*
*
* Semantically this is equivalent to an optimise Promise<Void>, but
* callback is a more meaningful name than EmptyPromise
*
*/
public interface Callback {
/**
* Instance of Adapter that can be used when the callback methods need an
* empty implementation without incurring in the cost of allocating a new
* Adapter object.
*/
public static Callback NOOP = new Callback() {
@Override
public void succeeded() {
}
@Override
public void failed(Throwable x) {
}
@Override
public boolean isNonBlocking() {
return false;
}
};
/**
*
* Callback invoked when the operation completes.
*
*
* @see #failed(Throwable)
*/
public void succeeded();
/**
*
* Callback invoked when the operation fails.
*
*
* @param x
* the reason for the operation failure
*/
public void failed(Throwable x);
/**
* @return True if the callback is known to never block the caller
*/
public boolean isNonBlocking();
/**
* Callback interface that declares itself as non-blocking
*/
public abstract class NonBlocking implements Callback {
@Override
public boolean isNonBlocking() {
return true;
}
}
class Nested implements Callback {
private final Callback callback;
public Nested(Callback callback) {
this.callback = callback;
}
public Nested(Nested nested) {
this.callback = nested.callback;
}
@Override
public void succeeded() {
callback.succeeded();
}
@Override
public void failed(Throwable x) {
callback.failed(x);
}
@Override
public boolean isNonBlocking() {
return callback.isNonBlocking();
}
}
}