摘要:從而可以啟動和取消異步計算任務查詢異步計算任務是否完成和獲取異步計算任務的返回結果。原理分析在分析中我們沒有看它的父類,其中有一個方法,返回一個,說明該方法可以獲取異步任務的返回結果。
FutureTask介紹
FutureTask是一種可取消的異步計算任務。它實現了Future接口,代表了異步任務的返回結果。從而FutureTask可以啟動和取消異步計算任務、查詢異步計算任務是否完成和獲取異步計算任務的返回結果。只有到異步計算任務結束時才能獲取返回結果,當異步計算任務還未結束時調用get方法會使線程阻塞。一旦異步計算任務完成,計算任務不能重新啟動或者取消,除非調用了runAndReset。
FutureTask實現了RunnableFuture,RunnableFuture結合了Future和Runnable。
FutureTask原理分析在ThreadPoolExecutor分析中我們沒有看它的父類AbstractExecutorService,其中有一個方法submit,返回一個Future,說明該方法可以獲取異步任務的返回結果。該方法有三個重載,可以接收Runnable和Callable,Callable是可以返回結果的一個Runnable,而Callable就是FutureTask的一個重要的變量。
@FunctionalInterface public interface CallableFutureTask的一些變量和狀態{ /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; }
/** * The run state of this task, initially NEW. The run state * transitions to a terminal state only in methods set, * setException, and cancel. During completion, state may take on * transient values of COMPLETING (while outcome is being set) or * INTERRUPTING (only while interrupting the runner to satisfy a * cancel(true)). Transitions from these intermediate to final * states use cheaper ordered/lazy writes because values are unique * and cannot be further modified. * * 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 Callablecallable; /** The result to return or exception to throw from get() */ //包裝返回結果或者異常,沒有被volatile修飾,狀態保護讀寫安全 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有7中狀態,介紹一下狀態之間的轉換:
NEW -> COMPLETING -> NORMAL:任務正常執行;
NEW -> COMPLETING -> EXCEPTIONAL:任務發生異常;
NEW -> CANCELLED:任務被取消;
NEW -> INTERRUPTING -> INTERRUPTED:任務被中斷;
public void run() { //如果state不為NEW,說明任務已經在執行或者取消 //如果設置運行線程失敗,說明任務已經有運行線程搶在前面 if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())) return; try { Callableset、setException和handlePossibleCancellationInterruptc = callable; //NEW狀態才可以執行 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() //將運行線程清空,在state被更改之前要保證runner非空,這樣能包裝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) { if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { outcome = t; UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state finishCompletion(); } }
當執行時發生異常,調用setException,首先將state設置為COMPLETING,設置成功后將outcome設置為異常,然后將state設置為EXCEPTIONAL。
protected void set(V v) { if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { outcome = v; UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state finishCompletion(); } }
當callable執行成功并返回,調用set,首先將state設置為COMPLETING,設置成功后將結果設置為outcome,然后設置state為NORMAL。
finally中如果state為中斷,調用handlePossibleCancellationInterrupt:
private void handlePossibleCancellationInterrupt(int s) { // It is possible for our interrupter to stall before getting a // chance to interrupt us. Let"s spin-wait patiently. if (s == INTERRUPTING) while (state == INTERRUPTING) Thread.yield(); // wait out pending interrupt // assert state == INTERRUPTED; // We want to clear any interrupt we may have received from // cancel(true). However, it is permissible to use interrupts // as an independent mechanism for a task to communicate with // its caller, and there is no way to clear only the // cancellation interrupt. // // Thread.interrupted(); }
如果狀態一直是INTERRUPTING,稍稍等待。
finishCompletion和get在上面set和setException中最后都調用了finishCompletion方法:
private void finishCompletion() { // assert state > COMPLETING; //該方法必須在state > COMPLETING時調用 //從頭到尾喚醒WaitNode中阻塞的線程 for (WaitNode q; (q = waiters) != null;) { //設置棧頂為空 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; //如果next為空,break if (next == null) break; q.next = null; // unlink to help gc q = next; } break; } } done(); callable = null; // to reduce footprint }
在調用get方法時,如果任務還在執行,線程會阻塞,FutureTask會將阻塞的線程放入waiters單鏈表。等待任務結束時被喚醒,我們繼續看get方法:
public V get() throws InterruptedException, ExecutionException { int s = state; if (s <= COMPLETING) //如果任務還在執行,阻塞當前線程,放入waiters單鏈表 s = awaitDone(false, 0L); 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 (;;) { //如果線程被中斷,移除當前node,拋出異常 if (Thread.interrupted()) { removeWaiter(q); throw new InterruptedException(); } int s = state; //如果任務完成或者被取消,直接返回 if (s > COMPLETING) { if (q != null) q.thread = null; return s; } //如果任務正在執行,線程等待一下 else if (s == COMPLETING) // cannot time out yet Thread.yield(); //如果q為空,新建一個node else if (q == null) q = new WaitNode(); //如果還未入列,嘗試將新建的node放入鏈表 else if (!queued) queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q); //如果設置了超時且超時了 else if (timed) { nanos = deadline - System.nanoTime(); if (nanos <= 0L) { //超時,移除node removeWaiter(q); return state; } //阻塞線程 LockSupport.parkNanos(this, nanos); } //阻塞當前線程 else LockSupport.park(this); } }removeWaiter
private void removeWaiter(WaitNode node) { if (node != null) { //設置節點的線程為空,做刪除標記 node.thread = null; retry: for (;;) { // restart on removeWaiter race for (WaitNode pred = null, q = waiters, s; q != null; q = s) { s = q.next; //thread不為空,continue if (q.thread != null) pred = q; //thread為空且pred不為空 else if (pred != null) { //刪除q pred.next = s; //檢查一下pred的thread,如果被其他線程修改,retry outer loop if (pred.thread == null) // check for race continue retry; } //thread為空且pred為空說明q為棧頂,將q.next設置為棧頂,失敗則retry else if (!UNSAFE.compareAndSwapObject(this, waitersOffset, q, s)) continue retry; } break; } } }report方法
get方法最后調用了report方法:
private V report(int s) throws ExecutionException { Object x = outcome; //NORMAL表示任務執行正常,返回結果 if (s == NORMAL) return (V)x; //任務被取消,拋出異常 if (s >= CANCELLED) throw new CancellationException(); //其他情況只有可能發生異常,拋出該異常 throw new ExecutionException((Throwable)x); }cancel方法
最后看一下cancel方法:
public boolean cancel(boolean mayInterruptIfRunning) { //當state不為NEW說明任務已經開始,不能被取消,返回false //當設置state失敗時,返回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; //中斷線程 if (t != null) t.interrupt(); } finally { // final state //設置任務為INTERRUPTED UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); } } } finally { finishCompletion(); } return true; }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/70968.html
摘要:本文的源碼基于。人如其名,包含了和兩部分。而將一個任務的狀態設置成終止態只有三種方法我們將在下文的源碼解析中分析這三個方法。將棧中所有掛起的線程都喚醒后,下面就是執行方法這個方法是一個空方 前言 系列文章目錄 有了上一篇對預備知識的了解之后,分析源碼就容易多了,本篇我們就直接來看看FutureTask的源碼。 本文的源碼基于JDK1.8。 Future和Task 在深入分析源碼之前,我...
摘要:主要的實現實際上運行還是一個,它對做了一個封裝,讓開發人員可以從其中獲取返回值是有狀態的共種狀態,四種狀態變換的可能和的區別通過方法調用有返回值可以拋異常結果的實現原理判斷狀態非狀態則直接進入返回結果處于狀態,則進入等待流程獲 主要的實現FutureTask # FutureTask實際上運行還是一個runnable,它對callable做了一個封裝,讓開發人員可以從其中獲取返回值; ...
摘要:為了避免一篇文章的篇幅過長,于是一些比較大的主題就都分成幾篇來講了,這篇文章是筆者所有文章的目錄,將會持續更新,以給大家一個查看系列文章的入口。 前言 大家好,筆者是今年才開始寫博客的,寫作的初衷主要是想記錄和分享自己的學習經歷。因為寫作的時候發現,為了弄懂一個知識,不得不先去了解另外一些知識,這樣以來,為了說明一個問題,就要把一系列知識都了解一遍,寫出來的文章就特別長。 為了避免一篇...
摘要:在分析它的源碼之前我們需要先了解一些預備知識。因為接口沒有返回值所以為了與兼容我們額外傳入了一個參數使得返回的對象的方法直接執行的方法然后返回傳入的參數。 前言 系列文章目錄 FutureTask 是一個同步工具類,它實現了Future語義,表示了一種抽象的可生成結果的計算。在包括線程池在內的許多工具類中都會用到,弄懂它的實現將有利于我們更加深入地理解Java異步操作實現。 在分析...
閱讀 1816·2019-08-30 13:54
閱讀 2730·2019-08-29 17:27
閱讀 1116·2019-08-29 17:23
閱讀 3355·2019-08-29 15:20
閱讀 1231·2019-08-29 11:28
閱讀 1575·2019-08-26 10:39
閱讀 1321·2019-08-26 10:29
閱讀 647·2019-08-26 10:13