Created
November 19, 2012 11:34
-
-
Save klausbrunner/4110226 to your computer and use it in GitHub Desktop.
A very simple implementation of the Java Future interface, for passing a single value to some waiting thread. Uses a CountdownLatch to ensure thread safety and provide blocking-with-timeout functionality required by Future. Cancellation isn't supported.
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
public final class ResultFuture implements Future<Result> { | |
private final CountDownLatch latch = new CountDownLatch(1); | |
private Result value; | |
@Override | |
public boolean cancel(boolean mayInterruptIfRunning) { | |
return false; | |
} | |
@Override | |
public boolean isCancelled() { | |
return false; | |
} | |
@Override | |
public boolean isDone() { | |
return latch.getCount() == 0; | |
} | |
@Override | |
public Result get() throws InterruptedException { | |
latch.await(); | |
return value; | |
} | |
@Override | |
public Result get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { | |
if (latch.await(timeout, unit)) { | |
return value; | |
} else { | |
throw new TimeoutException(); | |
} | |
} | |
// calling this more than once doesn't make sense, and won't work properly in this implementation. so: don't. | |
void put(Result result) { | |
value = result; | |
latch.countDown(); | |
} | |
} |
I was stumbling with the same questions on how to do this. I did not knew of the CountdownLatch - very useful.
I ended up adding an extra try { } finally ( ) on my methods that are called when I have a success or a failure and did a latch.countDown() on the finally just in case.
Thanks for this
Thank you for this example.
Really helped me out :)
Seems like it's possible to use framework's https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html to get the same (and more) features
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!!