FutureTask類淺析

#概述 FutureTask類是可取消式異步計算方法。該類是Future接口的基本實現。能夠開啓和取消異步計算,查詢異步計算結果是否完成,而且抽取出計算結果。計算結果只能在異步計算完成後被獲取。異步計算一旦完成,計算將不能被從新開始和取消。除非計算過程的調用使用了runAndReset方法。 Callable和Runnable類都可以包裝成FutureTask類。FutureTask自己實現了Runnable接口,並可以被提到Executor中去執行。 做爲獨立的類,其內部有protested方法用於執行任務。 #靜態方法塊java

try {
    //使用了unsafe設置state、runner和waiters的字段偏移量。
            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);
        }

#任務運行狀態 在FutureTask類中任務的運行狀態設置爲七種。 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; 任務運行狀態之間的轉換以下:app

NEW -> COMPLETING -> NORMAL
  NEW -> COMPLETING -> EXCEPTIONAL
  NEW -> CANCELLED
  NEW -> INTERRUPTING -> INTERRUPTED

#重要字段 //可執行任務 private Callable<V> callable; //異步計算結果或者get方法拋錯信息 private Object outcome; // non-volatile, protected by state reads/writes //執行任務的線程 private volatile Thread runner; //等待線程隊列 private volatile WaitNode waiters;異步

#重要方法 ##構造this

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 wrapper成callable
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

##任務取消線程

public boolean cancel(boolean mayInterruptIfRunning) {
        if (state != NEW)
            return false;
        if (mayInterruptIfRunning) {
            if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
                return false;
            Thread t = runner;
            if (t != null)
                t.interrupt();
            UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
        }
        else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
            return false;
        finishCompletion();
        return true;
    }

取消任務方法接收了一個布爾類型的變量 一、若是變量爲true,則首先嚐試將運行狀態設置爲interrupting,若是不容許則返回false,標示取消失敗。不然得到任務,作中斷操做,將對象的狀態字段置爲INTERRUPTED。 二、若是變量爲false或者未設置,則直接嘗試將任務狀態置爲cancelled,若是失敗則返回false,表示取消失敗。不然執行finishCompletion(),將全部線程隊列中等待的線程所有釋放掉。等待gc回收。 ##執行(任務不能被打斷)指針

public void run() {
        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);
        }
    }

任務運行首先判斷任務執行狀態,若是當前任務執行狀態不是new或者設置當前線程爲執行線程操做失敗,則返回空。 而後得到任務callable,若是任務狀態是new而且任務非空,則調用call()方法得到結果,若是在異步計算的過程當中拋異常則將返回null的結果。 最後繼續得到任務執行狀態,若是任務處於INTERRUPTING狀態,則處理中斷。code

##任務執行(容許reset)orm

protected boolean runAndReset() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return false;
        boolean ran = false;
        int s = state;
        try {
            Callable<V> c = callable;
            if (c != null && s == NEW) {
                try {
                    c.call(); // don't set result
                    ran = true;
                } catch (Throwable ex) {
                    setException(ex);
                }
            }
        } 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
            s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
        return ran && s == NEW;
    }

和前一個run方法不一樣的有兩個地方。第一個就是增長了一個boolean變量ran,第二個就是沒有設置result。 ##得到結果對象

public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

得到結果的方法首先判斷時間單位,若是未設置會拋空指針。而後得到任務運行狀態,若是狀態是未完成,而且等待指定時間後讓然沒有得到結果,則跑超時異常,不然運行 report(s)。接口

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);
    }

report(s)方法會判斷任務執行狀態,根據狀態是normal仍是cancelled分別返回執行結果或異常信息。

相關文章
相關標籤/搜索