并發(fā)編程系列之FutureTask源碼學(xué)習(xí)筆記

并發(fā)編程系列之FutureTask源碼學(xué)習(xí)筆記

1、什么是FutureTask類?

上一章節(jié)的學(xué)習(xí)中,我們知道了Future類的基本用法,知道了Future其實(shí)就是為了監(jiān)控線程任務(wù)執(zhí)行的,接著本博客繼續(xù)學(xué)習(xí)FutureTask。然后什么是FutureTask類?

Future是1.5版本引入的異步編程的頂層抽象接口,FutureTask則是Future的基礎(chǔ)實(shí)現(xiàn)類。同時(shí)FutureTask還實(shí)現(xiàn)了Runnable接口,所以FutureTask也可以作為一個(gè)獨(dú)立的Runnable任務(wù)。

2、使用FutureTask封裝Callable任務(wù)

線程中是不能直接傳入Callable任務(wù)的,所以需要借助FutureTask,F(xiàn)utureTask可以用來(lái)封裝Callable任務(wù),下面給出一個(gè)例子:

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  修改內(nèi)容:
 * </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的源碼,可以看出實(shí)現(xiàn)了RunnableFuture接口

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

RunnableFuture接口是怎么樣的?可以看出其實(shí)是繼承了Runnable,F(xiàn)uture

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類圖:


在這里插入圖片描述

所以,可以說(shuō)FutureTask本質(zhì)就是一個(gè)Runnable任務(wù)

4、FutureTask源碼學(xué)習(xí)

  • FutureTask類屬性
public class FutureTask<V> implements RunnableFuture<V> {
    // 狀態(tài):存在以下7中狀態(tài)
    private volatile int state;
    // 新建
    private static final int NEW          = 0;
    // 任務(wù)完成中
    private static final int COMPLETING   = 1;
    // 任務(wù)正常完成
    private static final int NORMAL       = 2;
    // 任務(wù)異常
    private static final int EXCEPTIONAL  = 3;
    // 任務(wù)取消
    private static final int CANCELLED    = 4;
    // 任務(wù)中斷中
    private static final int INTERRUPTING = 5;
    // 任務(wù)已中斷
    private static final int INTERRUPTED  = 6;

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

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

  • 是一個(gè)Runnable任務(wù),run方法實(shí)現(xiàn)
public void run() {
     // 兩種情況直接返回
     // 1:狀態(tài)不是NEW,說(shuō)明已經(jīng)執(zhí)行過(guò),獲取已經(jīng)取消任務(wù),直接返回
     // 2:狀態(tài)是NEW,將當(dāng)前執(zhí)行線程保存在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 {
                // 執(zhí)行了給如的Callable任務(wù)
                result = c.call();
                ran = true;
            } catch (Throwable ex) {
                result = null;
                ran = false;
                // 異常的情況,設(shè)置異常
                setException(ex);
            }
            if (ran)
                // 任務(wù)正常執(zhí)行,設(shè)置結(jié)果
                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;
        // 任務(wù)被中斷,執(zhí)行中斷處理
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
}

setException方法:

protected void setException(Throwable t) {
  // CAS,將狀態(tài)由NEW改為COMPLETING(中間狀態(tài))
   if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        // 返回結(jié)果
        outcome = t;
        // 將狀態(tài)改為EXCEPTIONAL
        UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
        finishCompletion();
    }
}
  • get獲取執(zhí)行結(jié)果
public V get() throws InterruptedException, ExecutionException {
        int s = state;
        // 任務(wù)還沒(méi)完成,調(diào)用awaitDonw
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        // 返回結(jié)果
        return report(s);
    }

get超時(shí)的方法

public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        // unit是時(shí)間單位,必須傳
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        // 超過(guò)阻塞時(shí)間timeout,拋出TimeoutException
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

重點(diǎn)看下awaitDone方法:

private int awaitDone(boolean timed, long nanos)
    throws InterruptedException {
    // 計(jì)算截止時(shí)間
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    WaitNode q = null;
    // 
    boolean queued = false;
    // 無(wú)限循環(huán),判斷條件是否符合
    for (;;) {
        // 1、線程是否被中斷,是的情況,移除節(jié)點(diǎn),同時(shí)拋出InterruptedException
        if (Thread.interrupted()) {
            removeWaiter(q);
            throw new InterruptedException();
        }
        // 2、獲取當(dāng)前狀態(tài),如果狀態(tài)大于COMPLETING
        // 說(shuō)明任務(wù)完成了,有可能正常執(zhí)行完成,也有可能是取消了任務(wù)
        int s = state;
        if (s > COMPLETING) {
            if (q != null)
                // thread置為null 等待JVM gc
                q.thread = null;
                //返回結(jié)果
            return s;
        }
        //3、如果狀態(tài)處于中間狀態(tài)COMPLETING
        //表示任務(wù)已經(jīng)結(jié)束但是任務(wù)執(zhí)行線程還沒(méi)來(lái)得及給outcome賦值
        else if (s == COMPLETING) // cannot time out yet
            // 這種情況線程yield讓出執(zhí)行權(quán),給其它線程先執(zhí)行
            Thread.yield();
         // 4、如果等待節(jié)點(diǎn)為空,則構(gòu)造一個(gè)等待節(jié)點(diǎn)
        else if (q == null)
            q = new WaitNode();
       // 5、如果還沒(méi)有入隊(duì)列,則把當(dāng)前節(jié)點(diǎn)加入waiters首節(jié)點(diǎn)并替換原來(lái)waiters
        else if (!queued)
            queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                 q.next = waiters, q);
        else if (timed) {
            nanos = deadline - System.nanoTime();
            //如果需要等待特定時(shí)間,則先計(jì)算要等待的時(shí)間
            // 如果已經(jīng)超時(shí),則刪除對(duì)應(yīng)節(jié)點(diǎn)并返回對(duì)應(yīng)的狀態(tài)
            if (nanos <= 0L) {
                removeWaiter(q);
                return state;
            }
            // 阻塞等待特定時(shí)間
            LockSupport.parkNanos(this, nanos);
        }
        else
           // 讓線程等待,阻塞當(dāng)前線程
            LockSupport.park(this);
    }
}
  • cancel取消任務(wù)
public boolean cancel(boolean mayInterruptIfRunning) {
    // 如果任務(wù)已經(jīng)結(jié)束,則直接返回false
   if (!(state == NEW &&
         UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
             mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
       return false;
   try {    // in case call to interrupt throws exception
        // 需要中斷任務(wù)的情況
       if (mayInterruptIfRunning) {
           try {
               Thread t = runner;
               // 調(diào)用線程的interrupt來(lái)停止線程
               if (t != null)
                   t.interrupt();
           } finally { // final state
               // 修改狀態(tài)為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)) {
            // 無(wú)限循環(huán),遍歷waiters列表,喚醒節(jié)點(diǎn)中的線程,然后將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
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容