Skip to content

Instantly share code, notes, and snippets.

@klausbrunner
Created November 19, 2012 11:34
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save klausbrunner/4110226 to your computer and use it in GitHub Desktop.
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.
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();
}
}
@isihwan
Copy link

isihwan commented Oct 7, 2014

Thank you!!

@joantune
Copy link

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

@pa1511
Copy link

pa1511 commented Mar 31, 2017

Thank you for this example.
Really helped me out :)

@kskalski
Copy link

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