Created
June 19, 2015 19:30
-
-
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.
This file contains hidden or 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
| 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