| 13 | import java.util.concurrent.atomic.AtomicReference; |
| 14 | |
| 15 | public class FutureTask<T> implements RunnableFuture<T> { |
| 16 | private enum State { New, Canceling, Canceled, Running, Done }; |
| 17 | |
| 18 | private final AtomicReference<State> currentState; |
| 19 | private final Callable<T> callable; |
| 20 | private final Object notifyLock; |
| 21 | private volatile Thread runningThread; |
| 22 | private volatile T result; |
| 23 | private volatile Throwable failure; |
| 24 | |
| 25 | public FutureTask(final Runnable r, final T result) { |
| 26 | this(new Callable<T>() { |
| 27 | @Override |
| 28 | public T call() { |
| 29 | r.run(); |
| 30 | |
| 31 | return result; |
| 32 | } |
| 33 | }); |
| 34 | } |
| 35 | |
| 36 | public FutureTask(Callable<T> callable) { |
| 37 | currentState = new AtomicReference<State>(State.New); |
| 38 | this.callable = callable; |
| 39 | notifyLock = new Object(); |
| 40 | runningThread = null; |
| 41 | result = null; |
| 42 | failure = null; |
| 43 | } |
| 44 | |
| 45 | @Override |
| 46 | public void run() { |
| 47 | if (currentState.compareAndSet(State.New, State.Running)) { |
| 48 | runningThread = Thread.currentThread(); |
| 49 | try { |
| 50 | result = callable.call(); |
| 51 | } catch (Throwable t) { |
| 52 | failure = t; |
| 53 | } finally { |
| 54 | if (currentState.compareAndSet(State.Running, State.Done) || |
| 55 | currentState.get() == State.Canceled) { |
| 56 | /* in either of these conditions we either were not canceled |
| 57 | * or we already were interrupted. The thread may or MAY NOT |
| 58 | * be in an interrupted status depending on when it was |
| 59 | * interrupted and what the callable did with the state. |
| 60 | */ |
| 61 | } else { |
| 62 | /* Should be in canceling state, so block forever till we are |
| 63 | * interrupted. If state already transitioned into canceled |
| 64 | * and thus thread is in interrupted status, the exception should |
| 65 | * throw immediately on the sleep call. |
| 66 | */ |
| 67 | try { |
| 68 | Thread.sleep(Long.MAX_VALUE); |
| 69 | } catch (InterruptedException e) { |
| 70 | // expected |
| 71 | } |
| 72 | } |
nothing calls this directly
no outgoing calls
no test coverage detected