Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@isihwan isihwan commented Oct 7, 2014

Thank you!!

@joantune

This comment has been minimized.

Copy link

@joantune joantune commented Dec 26, 2016

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

This comment has been minimized.

Copy link

@pa1511 pa1511 commented Mar 31, 2017

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

@kskalski

This comment has been minimized.

Copy link

@kskalski kskalski commented May 31, 2017

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