併發編程系列之FutureTask源碼學習筆記

併發編程系列之FutureTask源碼學習筆記

1、什麼是FutureTask類?

上一章節的學習中,我們知道了Future類的基本用法,知道了Future其實就是爲了監控線程任務執行的,接着本博客繼續學習FutureTask。然後什麼是FutureTask類?

Future是1.5版本引入的異步編程的頂層抽象接口,FutureTask則是Future的基礎實現類。同時FutureTask還實現了Runnable接口,所以FutureTask也可以作爲一個獨立的Runnable任務

2、使用FutureTask封裝Callable任務

線程中是不能直接傳入Callable任務的,所以需要藉助FutureTask,FutureTask可以用來封裝Callable任務,下面給出一個例子:

package com.example.concurrent.future;

import java.util.Random;
import java.util.concurrent.*;

/**
 * <pre>
 *      FutureTask例子
 * </pre>
 * <p>
 * <pre>
 * @author nicky.ma
 * 修改記錄
 *    修改後版本:     修改人:  修改日期: 2021/08/28 18:04  修改內容:
 * </pre>
 */
public class FutureTaskExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask futureTask = new FutureTask(new CallableTask());
        Thread t = new Thread(futureTask);
        t.start();
        System.out.println(futureTask.get());
    }
    static class CallableTask implements Callable<Integer> {
        @Override
        public Integer call() throws Exception{
            Thread.sleep(1000L);
            return new Random().nextInt();
        }
    }
}

3、FutureTask UML類圖

翻下FutureTask的源碼,可以看出實現了RunnableFuture接口

public class FutureTask<V> implements RunnableFuture<V> {
// ...
}

RunnableFuture接口是怎麼樣的?可以看出其實是繼承了Runnable,Future

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();

}

在idea裏畫出FutureTask的uml類圖:



所以,可以說FutureTask本質就是一個Runnable任務

4、FutureTask源碼學習

  • FutureTask類屬性
public class FutureTask<V> implements RunnableFuture<V> {
    // 狀態:存在以下7中狀態
    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;

    // 支持結果返回的Callable任務
    private Callable<V> callable;
    
    // 任務執行結果:包含正常和異常的結果,通過get方法獲取
    private Object outcome; 
    
    // 任務執行線程
    private volatile Thread runner;
    
    // 棧結構的等待隊列,該節點是棧中的最頂層節點
    private volatile WaitNode waiters;
}
  • 構造方法
// 傳入callable任務
public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;       // ensure visibility of callable
}

// 傳入runnable任務、結果變量result
public FutureTask(Runnable runnable, V result) {
    this.callable = Executors.callable(runnable, result);
    this.state = NEW;       // ensure visibility of callable
}
    

  • 是一個Runnable任務,run方法實現
public void run() {
     // 兩種情況直接返回
     // 1:狀態不是NEW,說明已經執行過,獲取已經取消任務,直接返回
     // 2:狀態是NEW,將當前執行線程保存在runner字段(runnerOffset)中,如果賦值失敗,直接返回
    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任務
                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) {
  // CAS,將狀態由NEW改爲COMPLETING(中間狀態)
   if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        // 返回結果
        outcome = t;
        // 將狀態改爲EXCEPTIONAL
        UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
        finishCompletion();
    }
}
  • get獲取執行結果
public V get() throws InterruptedException, ExecutionException {
        int s = state;
        // 任務還沒完成,調用awaitDonw
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        // 返回結果
        return report(s);
    }

get超時的方法

public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        // unit是時間單位,必須傳
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        // 超過阻塞時間timeout,拋出TimeoutException
        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 {
    // 計算截止時間
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    WaitNode q = null;
    // 
    boolean queued = false;
    // 無限循環,判斷條件是否符合
    for (;;) {
        // 1、線程是否被中斷,是的情況,移除節點,同時拋出InterruptedException
        if (Thread.interrupted()) {
            removeWaiter(q);
            throw new InterruptedException();
        }
        // 2、獲取當前狀態,如果狀態大於COMPLETING
        // 說明任務完成了,有可能正常執行完成,也有可能是取消了任務
        int s = state;
        if (s > COMPLETING) {
            if (q != null)
                // thread置爲null 等待JVM gc
                q.thread = null;
                //返回結果
            return s;
        }
        //3、如果狀態處於中間狀態COMPLETING
        //表示任務已經結束但是任務執行線程還沒來得及給outcome賦值
        else if (s == COMPLETING) // cannot time out yet
            // 這種情況線程yield讓出執行權,給其它線程先執行
            Thread.yield();
         // 4、如果等待節點爲空,則構造一個等待節點
        else if (q == null)
            q = new WaitNode();
       // 5、如果還沒有入隊列,則把當前節點加入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);
    }
}
  • cancel取消任務
public boolean cancel(boolean mayInterruptIfRunning) {
    // 如果任務已經結束,則直接返回false
   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;
               // 調用線程的interrupt來停止線程
               if (t != null)
                   t.interrupt();
           } finally { // final state
               // 修改狀態爲INTERRUPTED
               UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
           }
       }
   } finally {
       finishCompletion();
   }
   return true;
}

finishCompletion方法:

private void finishCompletion() {
    // assert state > COMPLETING;
    for (WaitNode q; (q = waiters) != null;) {
        if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
            // 無限循環,遍歷waiters列表,喚醒節點中的線程,然後將Callable置爲null
            for (;;) {
                Thread t = q.thread;
                if (t != null) {
                    q.thread = null;
                    // 喚醒線程
                    LockSupport.unpark(t);
                }
                WaitNode next = q.next;
                if (next == null)
                    break;
               // 置爲null,讓JVM gc
                q.next = null; // unlink to help gc
                q = next;
            }
            break;
        }
    }

    done();
    
    callable = null;        // to reduce footprint
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章