Created
May 22, 2019 01:15
-
-
Save massahud/aa58aeed6c0ae74cb35ebd1b0b114980 to your computer and use it in GitHub Desktop.
Simple future value holder for async await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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