| 1 | package java.util.concurrent; |
| 2 | |
| 3 | public class FutureTask<V> implements RunnableFuture<V> { |
| 4 | private Callable<V> callable; |
| 5 | private V result; |
| 6 | private Throwable exception; |
| 7 | private boolean done; |
| 8 | private boolean cancelled; |
| 9 | |
| 10 | public FutureTask(Callable<V> callable) { |
| 11 | if (callable == null) throw new NullPointerException(); |
| 12 | this.callable = callable; |
| 13 | } |
| 14 | |
| 15 | public FutureTask(Runnable runnable, V result) { |
| 16 | if (runnable == null) throw new NullPointerException(); |
| 17 | this.callable = Executors.callable(runnable, result); |
| 18 | } |
| 19 | |
| 20 | public boolean cancel(boolean mayInterruptIfRunning) { |
| 21 | synchronized(this) { |
| 22 | if (done) return false; |
| 23 | cancelled = true; |
| 24 | done = true; |
| 25 | notifyAll(); |
| 26 | } |
| 27 | return true; |
| 28 | } |
| 29 | |
| 30 | public boolean isCancelled() { |
| 31 | synchronized(this) { |
| 32 | return cancelled; |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | public boolean isDone() { |
| 37 | synchronized(this) { |
| 38 | return done; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | public V get() throws InterruptedException, ExecutionException { |
| 43 | synchronized(this) { |
| 44 | while (!done) { |
| 45 | wait(); |
| 46 | } |
| 47 | if (cancelled) throw new CancellationException(); |
| 48 | if (exception != null) throw new ExecutionException(exception); |
| 49 | return result; |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { |
| 54 | if (unit == null) throw new NullPointerException(); |
| 55 | long millis = unit.toMillis(timeout); |
| 56 | long end = System.currentTimeMillis() + millis; |
| 57 | synchronized(this) { |
| 58 | while (!done) { |
| 59 | long delay = end - System.currentTimeMillis(); |
| 60 | if (delay <= 0) throw new TimeoutException(); |
nothing calls this directly
no outgoing calls
no test coverage detected