人生若只如初見,何事秋風悲畫扇。
這是本應該是一個很美妙的事情,但是所有的每秒都是在一瞬間。
Furture 的說明
關於 FutureTask
之前有講過,是在《【多線程】拿到Java多線程裏面的值》裏面。FutureTask
可以幫助我們在 N 個線程中去觸發執行或者取消邏輯。這裏就會牽扯到線程安全問題。在 FutureTask
裏面是怎麼把握這個線程安全的呢?進去看一下。
繼承關係
我們先看一下這個繼承關係:
FurtureTask 的運行中的狀態
/**
* 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;
這是當前任務的執行過程中的狀態。可能的狀態轉化爲:
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
也就是說,初始的狀態是 NEW
,COMPLETING
, INTERRUPTING
是裏面的中間過渡狀態,其他的都是 終止狀態。
狀態的改變
看這張圖:
狀態的改變只有三個: cancel
, set
, setException
。 在註釋中也提到了,在我們的這個執行的過程中,我們的這個狀態可以被 set
, 從而中斷了原來的執行。
我們看一下這幾個執行方法:
public boolean cancel(boolean mayInterruptIfRunning) {
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
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
FutureTask 裏面,怎麼去根據我們的這個狀態碼去做到後續操作的。比如說,我們的 get()
方法裏面:
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
我們先拿到我們的狀態碼,如果說,還處於 / 還沒到 COMPLETING , 就先等待 完成,如果狀態碼被改變了:
@SuppressWarnings("unchecked")
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);
}
這個判斷的過程還是很簡單也很好理解的。那我們再看這個 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 (;;) {
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();
else if (q == null)
q = new WaitNode();
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);
}
}
當用戶代碼向線程池提交任務後,一個最常見的後續操作就是阻塞(或帶超時的阻塞)等待任務結果。
如果說,我們的任務沒有完成,那這裏就要把 cas 加入到 隊列裏面去,用到了parkNanos/park
來阻塞我們的線程,直至喚醒。這個喚醒的過程有三個:
- 線程被中斷了;
- 超時阻塞
- 完成任務
FurtureTask 的任務執行
任務執行,主要的就是 run
方法了:
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);
}
}
大家可以看到,我們在運行結束後,他這裏是有一個 把結果進行 set
的操作的。
到此,這個 FurtureTask 算是完了。基本原理也就是這些。目前正好再用,就在一邊學習,一邊實操。