【源码笔记】FutureTask
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent; import java.util.concurrent.locks.LockSupport; /** * A cancellable asynchronous computation. This class provides a base * implementation of {@link Future}, with methods to start and cancel * a computation, query to see if the computation is complete, and * retrieve the result of the computation. The result can only be * retrieved when the computation has completed; the {@code get} * methods will block if the computation has not yet completed. Once * the computation has completed, the computation cannot be restarted * or cancelled (unless the computation is invoked using * {@link #runAndReset}). * * <p>A {@code FutureTask} can be used to wrap a {@link Callable} or * {@link Runnable} object. Because {@code FutureTask} implements * {@code Runnable}, a {@code FutureTask} can be submitted to an * {@link Executor} for execution. * * <p>In addition to serving as a standalone class, this class provides * {@code protected} functionality that may be useful when creating * customized task classes. * * @since 1.5 * @author Doug Lea * @param <V> The result type returned by this FutureTask's {@code get} methods */ public class FutureTask<V> implements RunnableFuture<V> { /* * Revision notes: This differs from previous versions of this * class that relied on AbstractQueuedSynchronizer, mainly to * avoid surprising users about retaining interrupt status during * cancellation races. Sync control in the current design relies * on a "state" field updated via CAS to track completion, along * with a simple Treiber stack to hold waiting threads. * * Style note: As usual, we bypass overhead of using * AtomicXFieldUpdaters and instead directly use Unsafe intrinsics. */ /** * The run state of this task, initially NEW. The run state * transitions to a terminal state only in methods set, * setException, and cancel. During completion, state may take on * transient values of COMPLETING (while outcome is being set) or * INTERRUPTING (only while interrupting the runner to satisfy a * cancel(true)). Transitions from these intermediate to final * states use cheaper ordered/lazy writes because values are unique * and cannot be further modified. * * Possible state transitions: * NEW -> COMPLETING -> NORMAL * NEW -> COMPLETING -> EXCEPTIONAL * NEW -> CANCELLED * NEW -> INTERRUPTING -> INTERRUPTED */ // 表示当前task的状态 // task的状态要及时让各线程知道,所以用volatile修饰 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; // 表示当前任务执行过程中发生了异常。内部封装的callable.run()向上抛出了异常 private static final int CANCELLED = 4; // 表示当前任务被取消 private static final int INTERRUPTING = 5; // 表示当前任务中断中 private static final int INTERRUPTED = 6; // 表示当前任务已中断 /** The underlying callable; nulled out after running */ // submit(runnable/callable) 提交的对象最后都会放到这个对象中 // runnable使用装饰者模式伪装成Callable private Callable<V> callable; /** The result to return or exception to throw from get() */ // 正常情况下:任务正常结束,outcome保存执行结果(callable返回值) // 非正常情况下:callable向上抛出异常,outcome保存异常 private Object outcome; // non-volatile, protected by state reads/writes /** The thread running the callable; CASed during run() */ // 当前任务被执行期间,保存当前执行任务的线程对象引用 private volatile Thread runner; /** Treiber stack of waiting threads */ // 因为会有很多线程去get当前任务的执行结果 // 所以这里使用栈来保存这些线程 private volatile WaitNode waiters; /** * Returns result or throws exception for completed task. * * @param s completed state value */ @SuppressWarnings("unchecked") private V report(int s) throws ExecutionException { // 正常情况下,outcome保存的是callable运行结束的结果 // 非正常情况下,保存的是callable抛出的异常 Object x = outcome; // 条件成立:当前任务状态正常结束 --> 直接返回callable计算结果 if (s == NORMAL) return (V)x; // 条件成立:canceled,被取消了 if (s >= CANCELLED) throw new CancellationException(); // 行到此处:说明发生了异常 --> callable实现的代码有问题 throw new ExecutionException((Throwable)x); } /** * Creates a {@code FutureTask} that will, upon running, execute the * given {@code Callable}. * * @param callable the callable task * @throws NullPointerException if the callable is null */ public FutureTask(Callable<V> callable) { if (callable == null) throw new NullPointerException(); // callable就是程序员自己实现的业务类 this.callable = callable; // 设置当前任务状态为NEW this.state = NEW; // ensure visibility of callable } /** * Creates a {@code FutureTask} that will, upon running, execute the * given {@code Runnable}, and arrange that {@code get} will return the * given result on successful completion. * * @param runnable the runnable task * @param result the result to return on successful completion. If * you don't need a particular result, consider using * constructions of the form: * {@code Future<?> f = new FutureTask<Void>(runnable, null)} * @throws NullPointerException if the runnable is null */ public FutureTask(Runnable runnable, V result) { // 使用装饰者模式,将runnable转换为callable接口 // 当前任务执行j结束时,结果可能为null也可能为传进来的值 this.callable = Executors.callable(runnable, result); this.state = NEW; // ensure visibility of callable } public boolean isCancelled() { return state >= CANCELLED; } public boolean isDone() { return state != NEW; } public boolean cancel(boolean mayInterruptIfRunning) { // 条件1:state == NEW // true --> 当前任务处于运行中,或者处于任务队列中 // 条件2:UNSAFE.compareAndSwapInt(this, stateOffset, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED)) // true --> 改变当前task的状态成功 -> 仅能有一个线程改变task的状态成功 // 条件1 && 条件2 // true --> 当前task的状态为NEW,且改变task的状态成功 // false -> 1.当前task的状态不为NEW // 2.当前task的状态为NEW但CAS state失败(多线程竞争失败) // false的话会直接返回 if (!(state == NEW && UNSAFE.compareAndSwapInt(this, stateOffset, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED))) return false; try { // in case call to interrupt throws exception // mayInterruptIfRunning若为true,则说明需要给正在运行的线程发一个中断信号 if (mayInterruptIfRunning) { try { // 执行当前futureTask的线程 Thread t = runner; // 有可能现在是null:当前任务在队列中还没有线程获取到它 if (t != null) // 说明runner正在执行当前task,发送一个中断信号 // 如果你的程序是响应中断的,则会走中断逻辑 // 如果你的程序不是响应中断的,则什么也不会发生 t.interrupt(); } finally { // final state // 设置任务状态为:中断完成 UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); } } } finally { // 唤醒所有get阻塞的线程 finishCompletion(); } return true; } /** * @throws CancellationException {@inheritDoc} */ public V get() throws InterruptedException, ExecutionException { // 获取当前任务的状态 int s = state; // 条件成立:未执行、正在执行、已完成 --> 调用get的外部线程会被阻塞在get方法上 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); } /** * Protected method invoked when this task transitions to state * {@code isDone} (whether normally or via cancellation). The * default implementation does nothing. Subclasses may override * this method to invoke completion callbacks or perform * bookkeeping. Note that you can query status inside the * implementation of this method to determine whether this task * has been cancelled. */ protected void done() { } /** * Sets the result of this future to the given value unless * this future has already been set or has been cancelled. * * <p>This method is invoked internally by the {@link #run} method * upon successful completion of the computation. * * @param v the value */ protected void set(V v) { // 使用CAS方式将当前任务状态设置为完成中 // 有可能会失败 --> 外部线程等不及了,直接在set执行CAS之前,将task取消了 if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { // 将执行结果赋值给outcome outcome = v; // 将执行结果赋值给outcome之后,马上将当前任务的状态设置为正常结束 UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state finishCompletion(); } } /** * Causes this future to report an {@link ExecutionException} * with the given throwable as its cause, unless this future has * already been set or has been cancelled. * * <p>This method is invoked internally by the {@link #run} method * upon failure of the computation. * * @param t the cause of failure */ protected void setException(Throwable t) { // 使用CAS方式将当前任务状态设置为完成中 // 有可能会失败 --> 外部线程等不及了,直接在set执行CAS之前,将task取消了 if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { // 将异常赋值给outcome outcome = t; // 将执行结果赋值给outcome之后,马上将当前任务的状态设置为正常结束 // 将当前任务状态修改为EXCEPTIONAL UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state finishCompletion(); } } // 线程执行的入口 // --> submit(runnabke/callable) // -> AbstractExecutorService : RunnableFuture<Void> ftask = newTaskFor(task, null); // new FutureTask<T>(runnable, value) // -> FutureTask : this.callable = Executors.callable(runnable, result); // --> execute(task) public void run() { // 条件1:state != NEW // true -> 说明当前task已经被执行过了,或者canceled了 // 总之,非NEW状态的任务,线程不处理了 // 条件2:!RUNNER.compareAndSet(this, null, Thread.currentThread())) // true -> 说明当前task没有被执行, // 注意,这个关系是,当前是一个正在运行的线程,在访问一个FutureTask的run方法,以期望运行这个task // 所以,如果这个task没有线程执行它,则当前线程应该去尝试执行它。 // 但是可能有多个线程竞争这一个task,所以使用CAS,只有一个线程能够执行成功。 // - 执行成功的类,代表获得了task执行的权力,所以应该继续完成run接下来的动作。 // - 执行失败的类,说明在多线程竞争中失败,没有执行task的权力,return。 // 总之,NEW状态的任务,如果没有竞争到执行的权力,则也不处理了 if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())) return; // 执行到此处,说明当前task的状态是NEW // 且,当前线程竞争到了执行task的权力 try { // callable就是程序员自己写的一些执行逻辑 Callable<V> c = callable; // 条件1:c != null --> 防止程序员直接提交一个null进来 // 条件2:state == NEW --> 防止外部线程cancel当前线程 if (c != null && state == NEW) { // 结果引用 V result; // callable.call()代码是否执行成功 boolean ran; try { // 调用程序员自己实现的callable或者装饰后的runnable result = c.call(); ran = true; } catch (Throwable ex) { // 说明程序员自己写的逻辑块有bug了 result = null; ran = false; setException(ex); } if (ran) // 能执行到这里,说明当前task执行成功 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); } } /** * Executes the computation without setting its result, and then * resets this future to initial state, failing to do so if the * computation encounters an exception or is cancelled. This is * designed for use with tasks that intrinsically execute more * than once. * * @return {@code true} if successfully run and reset */ protected boolean runAndReset() { if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())) return false; boolean ran = false; int s = state; try { Callable<V> c = callable; if (c != null && s == NEW) { try { c.call(); // don't set result ran = true; } catch (Throwable ex) { setException(ex); } } } 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 s = state; if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s); } return ran && s == NEW; } /** * Ensures that any interrupt from a possible cancel(true) is only * delivered to a task while in run or runAndReset. */ private void handlePossibleCancellationInterrupt(int s) { // It is possible for our interrupter to stall before getting a // chance to interrupt us. Let's spin-wait patiently. if (s == INTERRUPTING) while (state == INTERRUPTING) Thread.yield(); // wait out pending interrupt // assert state == INTERRUPTED; // We want to clear any interrupt we may have received from // cancel(true). However, it is permissible to use interrupts // as an independent mechanism for a task to communicate with // its caller, and there is no way to clear only the // cancellation interrupt. // // Thread.interrupted(); } /** * Simple linked list nodes to record waiting threads in a Treiber * stack. See other classes such as Phaser and SynchronousQueue * for more detailed explanation. */ static final class WaitNode { volatile Thread thread; volatile WaitNode next; WaitNode() { thread = Thread.currentThread(); } } /** * Removes and signals all waiting threads, invokes done(), and * nulls out callable. */ private void finishCompletion() { // assert state > COMPLETING; // q指向waters链表的头节点 for (WaitNode q; (q = waiters) != null;) { // 使用CAS把头节点置空 // 使用CAS设置waiters为null的原因:外部线程可以使用cancel取消当前任务,也会触发finishCompletion方法 if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) { // 行到此处,task的waiters已经被置空了 for (;;) { // q从头节点开始一直向后遍历 // 拿到q中的线程 Thread t = q.thread; // 如果线程不为空,则把线程唤醒 if (t != null) { // help gc q.thread = null; LockSupport.unpark(t); } // 如果q没有nx,则跳出循环 WaitNode next = q.next; if (next == null) break; q.next = null; // unlink to help gc q = next; } break; } } // 空方法 done(); // 将task的callable置空 callable = null; // to reduce footprint } /** * 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 { // 0 --> 不带超时 final long deadline = timed ? System.nanoTime() + nanos : 0L; // 引用当前线程 --> 封装成WaitNode对象 WaitNode q = null; // 表示当前线程WaitNode对象有没有入队 boolean queued = false; for (;;) { // --------------------------------------------------------------------------------------------------------- // Part2:线程被唤醒(可能是被正常唤醒,也可能是被其它线程使用中断唤醒) // --------------------------------------------------------------------------------------------------------- // 条件成立:说明当前线程唤醒 --> 被其它线程使用中断唤醒 // interrupted()返回true后,会将Thread的中断标记重置回false if (Thread.interrupted()) { // 当前线程node出队 removeWaiter(q); // 抛出中断异常 --> get()方法的调用处会收到中断异常,而不是得到结果 throw new InterruptedException(); } // 假设当前线程是被其它线程使用unpack(thread)唤醒的话,会正常自旋,走下面逻辑 // 获取当前任务最新状态 int s = state; // 条件成立:说明当前任务已经有结果了 if (s > COMPLETING) { if (q != null) // help gc q.thread = null; // 直接返回当前状态 return s; } // 条件成立说明当前任务接近完成 else if (s == COMPLETING) // cannot time out yet // 让当前线程释放一次cpu,之后再进行下一次抢占 Thread.yield(); // --------------------------------------------------------------------------------------------------------- // Part1:线程在get()中判断当前线程还未结束(s <= COMPLETING) // --> 线程还没有结果 // --> 应该park当前线程,等待别的线程唤醒 // --------------------------------------------------------------------------------------------------------- // 条件成立:第一次自旋,当前线程还未创建WaitNode对象 --> 为当前线程创建WaitNode对象 else if (q == null) { q = new java.util.concurrent.FutureTask.WaitNode(); } // 条件成立:第二次自旋,当前线程已经创建了WaitNode对象,但是还未入队 --> 入队(头插) // waiters一直指向队列的头 else if (!queued) { // 如果CAS失败,则说明其它线程先一步插入了WaiteNode queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q); } // 第三次自旋 // Case1.带超时 else if (timed) { nanos = deadline - System.nanoTime(); if (nanos <= 0L) { removeWaiter(q); return state; } LockSupport.parkNanos(this, nanos); } // Case2.不带超时 else // park当前线程 -> 线程状态会变成WAITING状态 -> 相当于休眠了 // 除非有其它线程将当前线程唤醒或者中断 LockSupport.park(this); } } /** * Tries to unlink a timed-out or interrupted wait node to avoid * accumulating garbage. Internal nodes are simply unspliced * without CAS since it is harmless if they are traversed anyway * by releasers. To avoid effects of unsplicing from already * removed nodes, the list is retraversed in case of an apparent * race. This is slow when there are a lot of nodes, but we don't * expect lists to be long enough to outweigh higher-overhead * schemes. */ private void removeWaiter(WaitNode node) { if (node != null) { // 将node的thread置空,后续代码就清除所有thread为null的node node.thread = null; retry: for (;;) { // restart on removeWaiter race // 初始的pred为null // q为cur // s记录nx节点,初始不赋值 for (WaitNode pred = null, q = waiters, s; q != null; q = s) { // 为nx节点赋值,s在每一次遍历循环之初都指向cur的nx // q在初始的时候,指向waiter(链表头节点),之后每一次遍历,q都指向s,然后s再指向q的nx s = q.next; if (q.thread != null) // 如果q.thread不为null,则说明q是一个有效的节点 --> 挪动pred pred = q; // ------------------------- 行到此处,说明q.thread为null --> 需要从链表中摘除 ------------------------- // Case1.pred不为null else if (pred != null) { // pred指向nx pred.next = s; // ?? if (pred.thread == null) // check for race continue retry; } // Case2.pred为null --> waiters指向nx else if (!UNSAFE.compareAndSwapObject(this, waitersOffset, q, s)) continue retry; } break; } } } // 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); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)