Future模式

Future模式

异步调用实现,请求立即返回一个凭证,另起线程处理真正的实现

JDK中Future模式结构

在这里插入图片描述

Future

提供方法来检查计算是否完成,等待其完成,并检索计算结果

public interface Future<V> {
	//取消任务,mayInterruptIfRunning是否允许取消正在执行却没有执行完毕的任务
	boolean cancel(boolean mayInterruptIfRunning);
	//判断任务是否取消
	boolean isCancelled();
	//判断任务是否完成
	boolean isDone();
	//获取执行结果,如果任务还未执行完成会产生阻塞
	V get() throws InterruptedException, ExecutionException;
	//获取执行结果,指定时间内没获取到结果抛出TimeoutException
	V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

Callable

返回结果并可能引发异常的任务,与Runnable相比call方法有返回值且可向上抛出异常。

public interface Callable<V> {
    V call() throws Exception;
}

RunnableFuture

在成功执行run方法使完成Future并允许访问其结果

public interface RunnableFuture<V> extends Runnable, Future<V> {
	//设置执行结果,除非任务已被取消
    void run();
}

FutureTask

可取消的异步计算,提供了一个Future的基本实现

成员变量
//当前任务状态,线程间可见
private volatile int state;
private static final int NEW          = 0;
//任务已经完成,但结果还没有赋值给outcome
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<V> callable;
/** get()方法输出的结果 */
private Object outcome; // non-volatile, protected by state reads/writes
/** 异步执行任务的线程 */
private volatile Thread runner;
/** 获取任务结果的等待线程 */
private volatile WaitNode waiters;
内部类WaitNode

一个单链表来存储获取任务结果的等待线程

static final class WaitNode {
    volatile Thread thread;
    volatile WaitNode next;
    WaitNode() { thread = Thread.currentThread(); }
}
Future模式实现过程
run
  1. 通过构造器生成任务,传入Callable或Runnable+Value
  2. 当前执行线程调用run方法
    2.1. 判断任务状态是否NEW,CAS修改当前执行线程
    2.2. 调用Callable中的call方法,修改state,执行成功则设置返回值,如果发生异常则设置异常为返回结果
  3. finishCompletion方法调用,唤醒等待队列中的线程,同时清空等待队列
public class FutureTask<V> implements RunnableFuture<V> {
	//通过构造器生成一个任务
	public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        //设置执行体为当前Callable
        this.callable = callable;
        //设置任务状态为NEW
        this.state = NEW;       // ensure visibility of callable
    }
    public FutureTask(Runnable runnable, V result) {
    	//将给定的Runnable和结果通过RunnableAdapter转换为Callable类型
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }


	public void run() {
		//如果任务状态不为NEW或
		//CAS修改执行任务线程失败则直接返回,CAS比较null是为了保证只有一个线程在执行这个任务
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            //任务体不为空且状态为NEW
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                	//当前线程执行任务体并获得返回结果
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                	//如果执行过程出现异常则修改任务state,设置outcome为ex
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            //在任务处理完成前runner必须为非空,防止多个线程执行run方法
            runner = null;
            // 处理中断
            int s = state;
            //处理cancel(true)设置的中断
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

	//执行call方法完成后调用,唤醒等待队列中的线程
	private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
        	//将等待队列置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
  1. 当其他线程来获取操作返回的结果时,如果未完成则进入awaitDone
  2. awaitDone如果线程中断则退出等待队列并抛出异常,如果线程在awaitDone过程中完成了则退出,否则新建WaitNode并将其加入等待队列的头结点并挂起线程
  3. report根据任务状态返回不同结果(抛出异常,返回结果)
public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    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();
        else if (q == null)
        	//新建等待节点
            q = new WaitNode();
        else if (!queued)
        	//将当前线程加入等待队列的头结点,并将其next指向之前的头结点
            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);
    }
}
//根据状态返回结果
private V report(int s) throws ExecutionException {
    Object x = outcome;
    //正常执行完成
    if (s == NORMAL)
        return (V)x;
    //s>=4,任务被取消或中断则抛出取消异常
    if (s >= CANCELLED)
        throw new CancellationException();
    //任务执行中出现异常则抛出对应异常
    throw new ExecutionException((Throwable)x);
}
cancel
  1. 如果任务状态不为NEW并且CAS修改state失败
  2. 如果允许任务在执行中被取消则对执行任务的线程设置中断
  3. 唤醒等待队列中的线程,等待中的线程会抛出CancellationException异常
public boolean cancel(boolean mayInterruptIfRunning) {
   //如果任务状态不为NEW并且CAS修改state失败
   if (!(state == NEW &&
          UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
              mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
        return false;
    try {    // 如果允许任务在执行中被取消
        if (mayInterruptIfRunning) {
            try {
                Thread t = runner;
                if (t != null)
                	//对执行任务的线程设置中断
                    t.interrupt();
            } finally { // final state
                UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
            }
        }
    } finally {
    	//唤醒等待队列中的线程
        finishCompletion();
    }
    return true;
}

总结

FutureTask定义一个任务,任务可以是Callable或Runnable,然后将FutureTask交给线程执行,在此同时主线程可以做其他事,直到需要获得任务执行结果时调用FutureTask的get方法获得执行结果(如果未执行完成则阻塞主线程)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值