FutureTask源码分析

在这里插入图片描述

FutureTask源码分析

FutureTask成员

FutureTask基本变量
/**
     * 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
     */
    //注意volatile变量,>1的状态都表示任务已经被执行完成(正常、异常或者取消)
    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;
waitNode
//FutureTask的内部类,get方法的等待队列
    static final class WaitNode {
	//线程
        volatile Thread thread;
        volatile WaitNode next;
        WaitNode() { thread = Thread.currentThread(); }
    }
CAS工具初始化
CAS工具初始化
    // 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);
        }
    }
任务、存储结果、执行任务的线程 、阻塞的线程队列
   /** 任务 */
    private Callable<V> callable;
    /** 存储结果 */
    private Object outcome; // non-volatile, protected by state reads/writes
/** 执行任务的线程*/
    private volatile Thread runner;
    /** get方法阻塞的线程队列 */
    private volatile WaitNode waiters;
构造方法
/**
     * 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();
        this.callable = callable;
        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) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

这两个构造函数区别在于,如果使用第一个构造函数最后获取线程实行结果就是callable的执行的返回结果;而如果使用第二个构造函数那么最后获取线程实行结果就是参数中的result,接下来让我们看一下FutureTask的run方法。

FutureTask的各个方法

run方法
public void run() {
	//如果state不是new,以及runner值不是null就结束,否则将runner赋值当前线程。
        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);
        }
    }
setException方法
protected void setException(Throwable t) {
	//发生异常将status变成COMPLETING代表正在处理
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            //赋值异常结果
	    outcome = t;
	    //处理完之后变成EXCEPTIONAL
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            //唤醒get方法阻塞的线程
	    finishCompletion();
        }
    }
set方法
//同setException把status改为NORMAL
protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }
finishCompletion方法
private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
	   //看当前阻塞线程是不是q
            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;
		    //如果next不为空,将next赋值当前线程,并将next置空
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }
	//此方法,子类可以覆盖,实现回掉。
        done();

        callable = null;        // to reduce footprint
    }
get方法
//没有超时时间
public V get() throws InterruptedException, ExecutionException {
        int s = state;
	//<=completing代表还没执行完或者还没开始执行
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }
//设置了超时时间
public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
	//<=completing代表还没执行完或者还没开始执行
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }
awaitDone方法
private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
	//如果有超时时间nanos,那么过期的时间为System.nanoTime() + nanos
        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();
	   //也可以理解为s==NEW
            else if (q == null)
                q = new WaitNode();
	  //如果当前节点尚未入队,则将当前节点放到waiters中的首节点,并替换旧的waiters
            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);
        }
    }

removeWaiter方法

private void removeWaiter(WaitNode node) {
        if (node != null) {
            node.thread = null; // 将移除的节点的thread=null, 为移除做标示
            retry:
            for (;;) {          // restart on removeWaiter race
                for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
                    s = q.next;
                    //通过 thread 判断当前 q 是否是需要移除的 q节点,因为我们刚才标示过了
                    if (q.thread != null) 
                        pred = q; //当不是我们要移除的节点,就往下走
                    else if (pred != null) {
                        //当p.thread==null时,到这里。下面这句话,相当于把q从队列移除。
                        pred.next = s;
                        //pred.thread == null 这种情况是在多线程进行并发 removeWaiter 时产生的
                        //此时正好移除节点 node 和 pred, 所以loop跳到retry, 从新进行这个过程。想象一下,如果在并发的情况下,其他线程把pred的线程置为空了。那说明这个链表不应该包含pred了。所以我们需要跳到retry从新开始。
                        if (pred.thread == null) // check for race
                            continue retry;
                    }
                    //到这步说明p.thread==null 并且 pred==null。说明node是头结点。
                    else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                          q, s))
                        continue retry;
                }
                break;
            }
        }
    }

report方法

private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            return (V)x;//正常返回
        if (s >= CANCELLED)
            throw new CancellationException();//取消异常
        throw new ExecutionException((Throwable)x);//除了取消的其他异常
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值