0

I'm currently trying to understand the internals of java.util.concurrent.FutureTask implementation. I understand the purpose of the class, but the implementation looks complicated for me. Could someone provide intention comments for the awaitDone method?

/**
 * @throws CancellationException {@inheritDoc}
 */
public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    return report(s);
}

/**
 * Awaits completion or aborts on interrupt or timeout.
 *
 * @param timed true if use timed waits
 * @param nanos time to wait, if timed
 * @return state upon completion
 */
private int awaitDone(boolean timed, long nanos)
    throws InterruptedException {
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    WaitNode q = null;
    boolean queued = false;
    for (;;) {
        if (Thread.interrupted()) {
            removeWaiter(q);
            throw new InterruptedException();
        }

        int s = state;
        if (s > COMPLETING) {
            if (q != null)
                q.thread = null;
            return s;
        }
        else if (s == COMPLETING) // cannot time out yet
            Thread.yield();
        else if (q == null)
            q = new WaitNode();
        else if (!queued)
            queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                 q.next = waiters, q);
        else if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                removeWaiter(q);
                return state;
            }
            LockSupport.parkNanos(this, nanos);
        }
        else
            LockSupport.park(this);
    }
}

Right now I see that the code do something similar to

while(!isDone) {
    this.wait()
}
return result;

But I don't understand the purpose of deadline, q, and queued variables.

  • `deadline` is keeping track of the timeout - If we've waited for too long (i.e. if the current nanoTime() is past the content of `deadline`), we've timed out. – nickb Mar 31 '17 at 13:27
  • What @nickb said. And after we're timed out, we are supposed to abort whatever we were doing and complete wait with exception. `q` is an object that represents all threads that are currently waiting for us to complete (there may be more than one, so `WaitNode` also can have a `next` WaitNode). `queued` seems to be indicating that our current `WaitNode` is already queued, but that one I'm not sure about. – M. Prokhorov Mar 31 '17 at 14:00

0 Answers0