FutureTask源码学习

FutureTask

源码分析

(1)FutureTask属性集

   * Possible state transitions:
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED
     */
    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;

    /** The underlying callable; nulled out after running */
    private Callable callable;
    /** The result to return or exception to throw from get() */
    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 */
    private volatile WaitNode waiters;

FutureTask属性:

  • state属性记录当前线程的执行状态,用int表示0~6
  • callable属性在run方法中调用执行真正的业务逻辑
  • outcome属性该FutureTask返回值:异常/get()值
  • runner属性表示用来执行callable的线程,在run()/runAndReset()方法中通过CAS设置
  • waiters属性等待获取该FutureTask值的线程(们)

(2) FutureTask方法集
run方法:一般放在线程池中的线程中运行,运行过程中通过CAS重置该FutureTask的状态.

public void run() {
    //如果当前状态为NEW则设置runner为当前线程
    if (state != NEW ||!UNSAFE.compareAndSwapObject(this,runnerOffset,null, Thread.currentThread()))
        return;
    try {
        //在runner中调用callable.call()方法获取结果
        Callable 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);
    }
}

get方法:用于获取线程执行callable后的结果,当线程还没有执行完成时会调用awaitDone()使当前线程阻塞.

 public V get() throws InterruptedException, ExecutionException {
        int s = state;
        //如果当前状态为=0|1(未完成),则调用get()方法的线程进行阻塞.
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

set方法:通过CAS设置FutureTask的state及outcome属性

  //执行完毕将结果设置为outcome,并更改当前FutureTask状态
  protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }

cancle方法:取消线程的执行,首先重置FutureTask的状态然后中断该线程.

   public boolean cancel(boolean mayInterruptIfRunning) {
        if (!(state == NEW &&
              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }

finishCompletion方法:将所有的等待线程从队列中移除并唤醒,并设置callable为空.

private void finishCompletion() {
    // assert state > COMPLETING;
    for (WaitNode q; (q = waiters) != null;) {
        if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
            //唤醒因调用get()方法导致等待的所有线程
            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
}

awaitDone方法:等待runnable运行完成或中断,会调用LockSupport.park()方法使当线程中断.

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();
        }
        如果状态非normal,返回当前状态
        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);
    }
}

执行流程

  1. 第一步首先编写Callable实现类,重写V call()方法,submit(callable).
  2. 创建线程池,更新runner变量
  3. 客户端线程调用get()方法获取结果
  4. 添加到等待队列中,单链表连接
  5. 线程池任务执行成功,置状态
  6. 唤醒客户端线程并返回结果
  7. 获取submit()方法的返回值FutureTask对象
  8. 调用FutureTask对象,使当前线程阻塞直至有返回值.


    FutureTask源码学习_第1张图片
    Wechat.png

同步技巧

volatile变量

1. int state 变量在多线程之间(1.客户端线程:调用get()/cancle等()方法的线程 2.线程池中运行run()方法的runner线程)保证可见行
2. Thread runner 当在线程池中运行run()方法时设置池中线程
3. WaitNode waiters 在客户端线程中将waiter node添加到队列中,在线程池线程run()方法中将waiter node唤醒.

CAS

不用过于介绍主要是基于CAS从内存层面直接更改变量值

LockSupport

1. 底层调用UNSAFE的park() or unpark()方法阻塞/唤醒线程.
1. 调用该类的park()方法使线程进入阻塞状态.
2. 通过unpark()方法将线程重新唤醒.

demo

public class FutureCode {
public static void main(String[] args) {
    ArrayList> list = new ArrayList<>();
    ExecutorService pool = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 5; i++) {
        FutureTask ft = new FutureTask<>(new Task(i, "" + i));
        pool.submit(ft);
        list.add(ft);
    }
    System.out.println("计算完毕");

    Integer totalResult = 0;
    for (FutureTask ft : list) {
        try {
            totalResult = totalResult.intValue() + ft.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    pool.shutdown();
    System.out.println("多任务计算完毕:totalResult=" + totalResult);
}

static class Task implements Callable {
    private Integer result;
    private String name;

    public Task(Integer result, String name) {
        this.result = result;
        this.name = name;
    }

    @Override
    public Integer call() throws Exception {
        for (int i = 0; i < 100; i++) {
            result = +i;
        }
        Thread.sleep(5000);
        System.out.println("子线程计算任务:" + name + "执行完成!");
        return result;
    }
}
}

你可能感兴趣的:(FutureTask源码学习)