Skip to content

Instantly share code, notes, and snippets.

@daniellansun
Forked from klausbrunner/SimpleFuture.java
Created May 5, 2021 13:40
Show Gist options
  • Save daniellansun/c1aeba9a29255f37996b02dc1c00c5ad to your computer and use it in GitHub Desktop.
Save daniellansun/c1aeba9a29255f37996b02dc1c00c5ad 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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment