| 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 | } |
| 73 | |
| 74 | Thread.interrupted(); // reset interrupted status if set |
| 75 | handleDone(); |
| 76 | runningThread = null; // must be last operation |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | private void handleDone() { |
| 82 | done(); |