package java.util.concurrent;
public interface Future {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException;
}
package java.lang;
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
package java.util.concurrent;
public interface RunnableFuture extends Runnable, Future {
void run();
}
package java.util.concurrent;
@FunctionalInterface
public interface Callable {
V call() throws Exception;
}
注意:在获取结果的时候 需要阻塞线程,不是真正意义上的 异步。
package java.util.concurrent;
import java.util.concurrent.locks.LockSupport;
public class FutureTask implements RunnableFuture {
private volatile int state; //状态
private static final int NEW = 0; //new状态
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; //中断的 状态
private Callable callable;
private Object outcome; //最后结果
private volatile Thread runner;
private volatile WaitNode waiters; //获取结果的 等待线程;在别的线程 get 结果时候,本线程结果没有出来的时候,则会加入到 waiters 中去
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")); //state 的内存地址
runnerOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("runner")); //runner 的内存地址
waitersOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("waiters"));//waiters 的内存地址
} catch (Exception e) {
throw new Error(e);
}
}
//构造方法1
public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable 设置初始状态
}
//构造方法2
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result); //转化 runnable 为 callable ;在 任务运行成功之后,返回 result
this.state = NEW; // ensure visibility of callable 设置初始状态
}
//是否已经取消了任务
public boolean isCancelled() {
return state >= CANCELLED;
}
//任务是否已经完成
public boolean isDone() {
return state != NEW;
}
//run 方法
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread())) //如果runner是null,则设置 runner 为当前线程,并返回 true
return;
try {
Callable c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call(); //执行callable 的 run 方法
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result); //callable 的 run 方法 执行 成功后,设置 返回值 给 outcome
}
} 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);
}
}
//callable 的 run 方法 执行 成功后,设置 返回值 给 outcome,并更新 state 为 NORMAL
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion(); //移除所有等待的 线程
}
}
//callable 的 run 方法 执行 发生异常 后,设置 异常 给 outcome,并更新 state 为 EXCEPTIONAL
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion(); //移除所有等待的 线程
}
}
// 取消任务
public boolean cancel(boolean mayInterruptIfRunning) {
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED))) //设置 state 状态
return false;
try { // in case call to interrupt throws exception
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt(); //中断 这个 线程;注意这里只是 设置 此线程的 interrupt flag 具体的 中断 响应 需要 用户自己 处理
} finally { // final state
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); //设置 state 状态 为 INTERRUPTED
}
}
} finally {
finishCompletion(); //移除所有等待的 线程
}
return true;
}
//简单的 linked list 队列 记录等待线程
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
//移除所有等待的 线程
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
}
//报告结果
private V report(int s) throws ExecutionException {
Object x = outcome; //拿到最终结果
if (s == NORMAL) //运行没有异常的话 返回结果
return (V)x;
if (s >= CANCELLED) //运行出现 CANCELLED 及其之后的 状态的话,抛出 CancellationException
throw new CancellationException();
throw new ExecutionException((Throwable)x); //运行出现异常的话 抛出 异常
}
//阻塞式获取结果
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING) //还没有完成
s = awaitDone(false, 0L); //待 futureTask 的 run 执行完成之后,会在 set|setException 方法里面调用 finishCompletion 方法 ,唤醒所有的 等待线程;之后 这里就可以 继续执行了
return report(s);
}
//等待完成
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(); //让出 cpu,此线程暂停
else if (q == null)
q = new WaitNode(); //构造 WaitNode 实例
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q); //新增 本线程WaitNode 到 waiters 队列最前面
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this); //暂停当前线程,当 run 方法执行完成之后,会调用 LockSupport.unpark 继续执行
}
}
//从 waiters 队列中 移除 node.thread = null 的 所有节点
private void removeWaiter(WaitNode node) {
if (node != null) {
node.thread = null; //置 node.thread 为 null
retry:
for (;;) { // restart on removeWaiter race
for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
s = q.next;
if (q.thread != null)
pred = q; //继续向下遍历 node 节点
else if (pred != null) {
pred.next = s; //去除这个 null thread 的节点
if (pred.thread == null) // check for race
continue retry;
}
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
q, s))
continue retry;
}
break;
}
}
}
}
package java.util.concurrent;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.security.AccessControlException;
import sun.security.util.SecurityConstants;
public class Executors {
public static Callable callable(Runnable task, T result) { //转化 runnable 为 callable
if (task == null)
throw new NullPointerException();
return new RunnableAdapter(task, result);
}
//转化 runnable 为 callable ;在 任务运行成功之后,返回 result
static final class RunnableAdapter implements Callable {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}
}
Future 类通过 get() 方法阻塞等待获取异步执行的运行结果,性能比较差。
JDK1.8 中,Java 提供了 CompletableFuture 类,它是基于异步函数式编程。相对阻塞式等待返回结果,CompletableFuture 可以通过回调的方式来处理计算结果,实现了异步非阻塞,性能更优。
CompletableFuture 实现了 Future 和 CompletionStage 接口, 并提供了多种实现异步编程的方法,如supplyAsync, runAsync以及thenApplyAsync。
package java.util.concurrent;
import java.util.function.Supplier;
import java.util.function.Consumer;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.BiFunction;
import java.util.concurrent.Executor;
public interface CompletionStage {
//上一个task 正常结束,结果作为下一个task 的 入参
//上一个task 正常结束,结果作为下一个task 的 入参,最后返回结果
//同步串行 下一个 task
public CompletionStage thenApply(Function super T,? extends U> fn);
//异步串行 下一个 task
public CompletionStage thenApplyAsync(Function super T,? extends U> fn);
//异步串行 下一个 task;可以指定线程池
public CompletionStage thenApplyAsync(Function super T,? extends U> fn, Executor executor);
//上一个task 正常结束,结果作为下一个task 的 入参,最后不用返回结果
//同步串行 下一个 task
public CompletionStage thenAccept(Consumer super T> action);
//异步串行 下一个 task
public CompletionStage thenAcceptAsync(Consumer super T> action);
//异步串行 下一个 task;可以指定线程池
public CompletionStage thenAcceptAsync(Consumer super T> action, Executor executor);
//上一个task 正常结束,开始下一个task
//上一个task 正常结束,同步开始下一个task
public CompletionStage thenRun(Runnable action);
//上一个task 正常结束,异步开始下一个task
public CompletionStage thenRunAsync(Runnable action);
//上一个task 正常结束,异步开始下一个task ;可以指定线程池
public CompletionStage thenRunAsync(Runnable action, Executor executor);
//基于上一段 正常执行状态,执行下一阶段
//同步
public CompletionStage thenCompose(Function super T, ? extends CompletionStage> fn);
//异步
public CompletionStage thenComposeAsync(Function super T, ? extends CompletionStage> fn);
//异步 可以指定 线程池
public CompletionStage thenComposeAsync(Function super T, ? extends CompletionStage> fn, Executor executor);
//基于上一段 执行完毕的状态 执行下一阶段;消费其正常或者异常结果;即使 上一阶段 执行异常 也会执行 下一阶段
//同步
public CompletionStage handle(BiFunction super T, Throwable, ? extends U> fn);
//异步
public CompletionStage handleAsync(BiFunction super T, Throwable, ? extends U> fn);
//异步 可以指定 线程池
public CompletionStage handleAsync(BiFunction super T, Throwable, ? extends U> fn, Executor executor);
//基于上一段 执行完毕的状态和结果 执行下一阶段;消费其结果;即使 上一阶段 执行异常 也会执行 下一阶段
//同步
public CompletionStage whenComplete(BiConsumer super T, ? super Throwable> action);
//异步
public CompletionStage whenCompleteAsync(BiConsumer super T, ? super Throwable> action);
//异步 可以指定 线程池
public CompletionStage whenCompleteAsync(BiConsumer super T, ? super Throwable> action, Executor executor);
//上 二阶段 执行完成,开始执行下一阶段
//同步
public CompletionStage runAfterBoth(CompletionStage> other, Runnable action);
//异步
public CompletionStage runAfterBothAsync(CompletionStage> other, Runnable action);
//异步,可以指定 线程池
public CompletionStage runAfterBothAsync(CompletionStage> other, Runnable action, Executor executor);
//上两阶段执行完毕,开始下一阶段 结果作为参数 执行 fn 处理
//上两阶段执行完毕,开始下一阶段 结果作为参数 执行 fn 处理,返回结果
//同步
public CompletionStage thenCombine(CompletionStage extends U> other, BiFunction super T,? super U,? extends V> fn);
//异步
public CompletionStage thenCombineAsync(CompletionStage extends U> other, BiFunction super T,? super U,? extends V> fn);
//异步 可以指定 线程池
public CompletionStage thenCombineAsync(CompletionStage extends U> other, BiFunction super T,? super U,? extends V> fn, Executor executor);
//上两阶段执行完毕,结果作为 参数执行 函数,不返回结果
//同步
public CompletionStage thenAcceptBoth(CompletionStage extends U> other, BiConsumer super T, ? super U> action);
//异步
public CompletionStage thenAcceptBothAsync(CompletionStage extends U> other, BiConsumer super T, ? super U> action);
//异步,可以指定 线程池
public CompletionStage thenAcceptBothAsync(CompletionStage extends U> other, BiConsumer super T, ? super U> action, Executor executor);
//上两阶段 任何一个执行完成 结果作为参数 执行 函数 返回结果
//同步
public CompletionStage applyToEither(CompletionStage extends T> other, Function super T, U> fn);
//异步
public CompletionStage applyToEitherAsync(CompletionStage extends T> other, Function super T, U> fn);
//异步,可以指定 线程池
public CompletionStage applyToEitherAsync(CompletionStage extends T> other, Function super T, U> fn, Executor executor);
//上两阶段 任何一个执行完成 结果作为参数 执行 函数 不返回结果
//同步
public CompletionStage acceptEither(CompletionStage extends T> other, Consumer super T> action);
//异步
public CompletionStage acceptEitherAsync(CompletionStage extends T> other, Consumer super T> action);
//异步,可以指定 线程池
public CompletionStage acceptEitherAsync(CompletionStage extends T> other, Consumer super T> action, Executor executor);
//上两阶段 任何一个执行完成 执行下一阶段
//同步
public CompletionStage runAfterEither(CompletionStage> other, Runnable action);
//异步
public CompletionStage runAfterEitherAsync(CompletionStage> other, Runnable action);
//异步,可以指定 线程池
public CompletionStage runAfterEitherAsync(CompletionStage> other, Runnable action, Executor executor);
//上阶段异常处理
public CompletionStage exceptionally(Function fn);
//接口实现类之间的 相互转换
public CompletableFuture toCompletableFuture();
}
handle() | whenComplete() | exceptionly() | |
---|---|---|---|
访问成功 | Yes | Yes | No |
访问失败 | Yes | Yes | Yes |
能从失败中恢复 | Yes | No | Yes |
能转换结果从T 到 U | Yes | No | No |
成功时触发 | Yes | Yes | No |
失败时触发 | Yes | Yes | Yes |
有异步版本 | Yes | Yes | Yes(12版本) |
whenComplete() 并不能转换完成的结果。会内部抛出异常。
提供对异步计算的支持,可以通过回调的方式处理计算结果,CompletableFuture 类实现了CompletionStage和Future接口,所以还可以像之前使用Future那样使用CompletableFuture ,尽管已不再推荐这样用了。