1

recently,I read the source code about Java concurrent Jar,the code in FutureTask class is very hard to understand,the awaitDone method like this:

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);
    }
}

so,the question is ,I don't understand the usage of waiters, and how is the removeWaiter method worked.

any help would be appreciated.

lanbbz
  • 43
  • 1
  • 4

1 Answers1

0

According to the FutureTask javadocs, the waiters datastructure is a Treiber Stack, a lock-free data structure.

When one thread notices that the future is set or cancelled, it notifies any other waiting threads they can continue (un-parks them).

Stefan L
  • 1,529
  • 13
  • 20