Skip to content

Instantly share code, notes, and snippets.

@natemort
Created June 19, 2015 19:30
Show Gist options
  • Select an option

  • Save natemort/1b39f7f71d1cc392a322 to your computer and use it in GitHub Desktop.

Select an option

Save natemort/1b39f7f71d1cc392a322 to your computer and use it in GitHub Desktop.
A utility class I wrote that I keep coming back to. A class like this was added in Java 8 (https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html ), but if that's not an option, you've got this.
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Add a Future object that doesn't involve Runnables or anything fancy.
* It allows for checking for completion, waiting until completion, and getting the value.
* Nice and simple.
*
* @param <V>
*/
public class CompletionFuture<V> implements Future<V> {
private boolean complete;
private V value;
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return complete;
}
@Override
public synchronized V get() throws InterruptedException, ExecutionException {
if (!complete) {
wait();
}
return value;
}
@Override
public synchronized V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
if (!complete) {
wait(unit.toMillis(timeout));
}
return value;
}
public synchronized void complete(V value) {
this.value = value;
complete = true;
this.notifyAll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment