FutureTask被设计为一个可删除的异步计算任务,实现了RunnableFuture接口,提供了一系列方法来启动、删除任务、查询当前的计算状态,以及取回计算结果。要取回结果只能等到任务完成,因为取回结果的方法get(..)是一个阻塞方法,计算没结束时会一直等到结束,或超时、或中断。
FutureTask可以包装Callable或Runnable对象,然后可以提交给Executors来执行。
FutureTask提供了protected方法比如done(), 用户可在这些方法中定制任务。
run(), 是在Task线程(而非下发任务的线程)里运行的, c.call()是核心业务方法(所谓的计算)
public void run() { if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())) return; try { Callable<V> c = callable; if (c != null && state == NEW) { V result; boolean ran; try { result = c.call(); ran = true; } catch (Throwable ex) { result = null; ran = false; setException(ex); } if (ran) set(result); } } finally { // runner must be non-null until state is settled to // prevent concurrent calls to run() runner = null; // state must be re-read after nulling runner to prevent // leaked interrupts int s = state; if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s); } }
计算结束后调用set设置结果:
protected void set(V v) { if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { outcome = v; UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state finishCompletion(); } }
sdk5开始,concurrent包中的并发处理大量使用了CAS, 这里set方法也用CAS来改变任务执行的状态(注意当前代码是在Task线程里执行的),stateOffset是当前任务的状态标志state在FutureTask对象中的偏移量。
private volatile int state; private static final int NEW = 0; private static final int COMPLETING = 1; private static final int NORMAL = 2; private static final int EXCEPTIONAL = 3; private static final int CANCELLED = 4; private static final int INTERRUPTING = 5; private static final int INTERRUPTED = 6; ... // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long stateOffset; private static final long runnerOffset; private static final long waitersOffset; static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<?> k = FutureTask.class; stateOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("state")); runnerOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("runner")); waitersOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("waiters")); } catch (Exception e) { throw new Error(e); } }
任务完成后会释放等待结果的线程(一般是下发任务的线程),finishCompletion()是Treiber算法的实现,它的作用就是实现一个线程安全的非阻塞式的栈 。 那么这些阻塞的线程哪里来的呢? 前面说过,取得结果的get方法是个阻塞方法,如果在计算有结果前调用会导致等待。
/** * Removes and signals all waiting threads, invokes done(), and * nulls out callable. */ private void finishCompletion() { // assert state > COMPLETING; for (WaitNode q; (q = waiters) != null;) { if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) { for (;;) { Thread t = q.thread; if (t != null) { q.thread = null; LockSupport.unpark(t); } WaitNode next = q.next; if (next == null) break; q.next = null; // unlink to help gc q = next; } break; } } done(); callable = null; // to reduce footprint }
get方法可以设置超时时间。从其调用的awaitDone方法可以看出,如果还没有计算结果的话, 等待结果的线程,即调用get方法的线程(一般是下发任务的线程)会通过LockSuppport类挂起。 这里也用到了CAS, 有CAS的场景一般就会出现while(true) 或 for(;;)这样的循环 ==!。 到这里,回头看一下前面的finishCompletion()方法,整个流程基本就清楚了。
public V get() throws InterruptedException, ExecutionException { int s = state; if (s <= COMPLETING) s = awaitDone(false, 0L); return report(s); } /** * @throws CancellationException {@inheritDoc} */ public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (unit == null) throw new NullPointerException(); int s = state; if (s <= COMPLETING && (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING) throw new TimeoutException(); return report(s); } /** * 等待结果完成、或者被意外中断、或者等待超时. * * @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); } }