Runnable,Callable,Future關係淺析

hahaeee發表於2018-03-20

Runnable,Callable在ThreadPoolExecutor中的使用

在使用ExecutorService的使用一般會使用submit()方法提交runnable或者callable

看一下AbstractExecutorService中的實現

//java.util.concurrent.AbstractExecutorService
public Future<?> submit(Runnable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<Void> ftask = newTaskFor(task, null);
    execute(ftask);
    return ftask;
}

public <T> Future<T> submit(Callable<T> task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<T> ftask = newTaskFor(task);
    execute(ftask);
    return ftask;
}
複製程式碼

可以看到都通過newTaskFor()方法生成一個RunnableFuture物件

protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
 	return new FutureTask<T>(runnable, value);
}

    
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
	return new FutureTask<T>(callable);
}
複製程式碼

看一下RunnableFuture的構造

//java.util.concurrent.FutureTask
public FutureTask(Callable<V> callable) {
     if (callable == null)
     throw new NullPointerException();
     this.callable = callable;
     this.state = NEW;       // ensure visibility of callable
}

public FutureTask(Runnable runnable, V result) {
  	//包裝runnable->callable
    this.callable = Executors.callable(runnable, result);
    this.state = NEW;       // ensure visibility of callable
}

//java.util.concurrent.Executors
public static <T> Callable<T> callable(Runnable task, T result) {
    if (task == null)
    throw new NullPointerException();
    return new RunnableAdapter<T>(task, result);
}

//java.util.concurrent.Executors.RunnableAdapter
//介面卡模式 runnable->callable
static final class RunnableAdapter<T> implements Callable<T> {
    final Runnable task;
    final T result;
    RunnableAdapter(Runnable task, T result) {
      this.task = task;
      this.result = result;
    }
    public T call() {
      task.run();
      return result;
    }
}

複製程式碼

從上面程式碼可以看submit(Runnable)和submit(Callable)方法的實現步驟

  1. 判空
  2. 生成RunnableFuture物件
  3. 呼叫execute()方法
 //java.util.concurrent.ThreadPoolExecutor
 
 //任務佇列
 private final BlockingQueue<Runnable> workQueue;
 
 public void execute(Runnable command) {
       ...
       workQueue.offer(command)
       ...
 }
複製程式碼

從execute(Runnable)方法簽名可以得出: RunnableFuture是個Runnable實現類

FutureTask是RunnableFuture的實現類

看一下FutureTask的繼承關係

FutureTask

RunnableFuture是一個介面卡模式的實現 將Future適配為Runable

看一下FutureTask是如何實現Runnable介面的

 public void run() {
 		...
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    //執行callable.call()方法
                    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);
        }
    }
複製程式碼

總結:

  1. ThreadPoolExecutor中的任務佇列存放的Runnable物件
  2. 通過execute方法提交的Runable物件會被直接塞到任務佇列中
  3. 通過submit(Callable)方法提交的Callable物件會被包裝FutureTask物件,再塞到任務佇列中
  4. 通過submit(Runnable)方法提交的Runnable會被包裝成RunnableAdapter物件(Callable實現),再包成FutureTask物件,再塞到任務佇列中

Future

Future:一個非同步計算的佔位物件,用於獲取一個將被計算的結果

Future

Future特性:

  1. 通過get()獲取一個將被計算的結果
  2. 通過cancel()方法取消對結果的計算

FutureTask.cancel()實現

FutureTask的幾種狀態

    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;
    
   	//可能出現的狀態變化過程
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED
複製程式碼

cancel實現過程

public boolean cancel(boolean mayInterruptIfRunning) {
  		// 1.狀態判斷 
  		// 只有state==New且通過cas修改state值成功 才往下執行 否則return false
        if (!(state == NEW &&
              //狀態變化
              // mayInterruptIfRunning? NEW->INTERRUPTING:NEW->CANCELLED
              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {//2.打斷執行
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // INTERRUPTING->INTERRUPTED
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
          	//3.結束
            finishCompletion();
        }
        return true;
    }
複製程式碼

過程分析:

  1. 狀態判斷

    if表示式可以拆分成 state == NEW 和 UNSAFE.compareAndSwapInt(this, stateOffset, NEW,mayInterruptIfRunning ? INTERRUPTING : CANCELLED)

    1. state == NEW 判斷當前狀態是否為NEW

    2. UNSAFE.compareAndSwapInt(this, stateOffset, NEW,mayInterruptIfRunning ? INTERRUPTING : CANCELLED)

      這是一個cas的修改方式 相當於state=mayInterruptIfRunning ? INTERRUPTING : CANCELLED

      cas的方式主要出於原子性的考慮

      unsafe的用法請自行查閱資料

    總結:如果狀態為NEW 且 獲取到鎖 方可執行真正的cancle操作

  2. 打斷執行

    mayInterruptIfRunning?thread.interrupt() : 無操作 ;

  3. 結束

    finishCompletion();

    cancel狀態變化及流程圖

    總結:

    1. 只有state==NEW時才可以進行cancel
    2. 通過unsafe的cas操作修改state
    3. 狀態變化兩條線
      1. NEW->CANCLE
      2. NEW->INTERRUPTING->INTERRUPTED

FutureTask.run()實現

public void run() {
  	// 1.狀態判斷 
  	// 只有state==New且通過cas設定runner值成功 才往下執行 否則return false
    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 {
              	//執行callable.call()
                result = c.call();
                ran = true;
            } catch (Throwable ex) {
                result = null;
                ran = false;
              	//NEW->COMPLETING->EXCEPTIONAL
                setException(ex);
            }
            if (ran)//NEW->COMPLETING->NORMAL
                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);
    }
}
 protected void setException(Throwable t) {
   	// 防止cancle()方法修改state
    if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        outcome = t;
        UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
        finishCompletion();
    }
}
 protected void set(V v) {
   	// 防止cancle()方法修改state
    if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        outcome = v;
        UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
        finishCompletion();
    }
}
複製程式碼

總結:

  1. 只有state==NEW時方法執行run()過程
  2. 通過unsafe的cas設定runner(當前執行緒)
  3. 狀態變化 兩條線:
    1. NEW->COMPLETING->EXCEPTIONAL
    2. NEW->COMPLETING->NORMAL

cancle()總結

  1. 如果run()尚未被執行 則將callable置空且修改狀態為非NEW(這樣run()方法就不會執行)
  2. 如果run()正在執行且callable.call()尚未執行完成 則呼叫thread.interrpt()通知執行緒停止(只是通知 無法保證打斷執行緒 具體原因自行查閱interrpt()資料) 由於cancle修改了state狀態 所以setException()和set()無法儲存結果
  3. 如果run()執行完畢 或者 callable.call()執行完成 由於 state!=NEW 所以cancle()不繼續執行 返回失敗

FutureTask.get()實現

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 (;;) {
      	//cancle()過程中呼叫thread.interrupt()則退出迴圈 並拋異常
        if (Thread.interrupted()) {
            removeWaiter(q);
            throw new InterruptedException();
        }

        int s = state;
        if (s > COMPLETING) {//執行完成(包括執行異常) 或被取消 返回當前status
            if (q != null)
                q.thread = null;
            return s;
        }
        else if (s == COMPLETING) //執行完成但尚未修改狀態 則Thread.yield()讓出cpu資源
            Thread.yield();
        else if (q == null)//尚未執行完成 則加入生成等待節點
            q = new WaitNode();
        else if (!queued)//當前等待節點尚未加入等待佇列 則cas方式加入等待佇列
            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);
    }
}
//根據state 返回不同結果
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);
}

//run()和cancle()最終都會呼叫finishCompletion() 分析是如何喚醒等待佇列中的節點的
private void finishCompletion() {
    // assert state > COMPLETING;
    for (WaitNode q; (q = waiters) != null;) {
        // cas方式修改將等待佇列置空
        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;        // callable置空
}
複製程式碼

get()總結:

  1. 生成等待節點並加入等待佇列中
  2. 通過LockSupport.park() 進行自旋 等待被喚醒
  3. 根據state包裝任務執行結果

相關文章