Skip to content

Instantly share code, notes, and snippets.

@massahud
Created May 22, 2019 01:15
Show Gist options
  • Save massahud/aa58aeed6c0ae74cb35ebd1b0b114980 to your computer and use it in GitHub Desktop.
Save massahud/aa58aeed6c0ae74cb35ebd1b0b114980 to your computer and use it in GitHub Desktop.
Simple future value holder for async await
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Phaser;
public class FutureValue<T> {
private T value = null;
private Exception ex = null;
private Phaser phaser = new Phaser(1);
/**
* Get blocks until a value or an exception is set, after that it always
* returns immediately
*
* @return the value
* @throws ExecutionException
*/
public T get() throws ExecutionException {
phaser.register();
phaser.arriveAndAwaitAdvance();
if (ex != null) {
throw new ExecutionException(ex);
}
return value;
}
/**
* Sets the value and unblocks awaiting threads
*
* @param val
*/
public void set(T val) {
this.value = val;
phaser.forceTermination();
}
/**
* Sets an exception and unblocks awaiting threads
*/
public void setException(InterruptedException ex) {
this.ex = ex;
phaser.forceTermination();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment