摘要:序本文主要解析一下的超時原理。這里等待超時,然后返回原始狀態小結由此可見,超時的機制其實不能中斷里頭實際執行的動作,超時只是讓調用線程能夠在指定時間返回而已,而底層調用的方法,實際還在執行。這里是需要額外注意的。
序
本文主要解析一下futureTask的超時原理。
實例ExecutorService executor = Executors.newFixedThreadPool(1); Future> future = executor.submit( new Callable() { public Void call() throws Exception { //do something return null; } }); future.get(500, TimeUnit.MILLISECONDS);
submit里頭構造的是java/util/concurrent/ThreadPoolExecutor.java
java/util/concurrent/AbstractExecutorService.java
publicexecuteFuture submit(Callable task) { if (task == null) throw new NullPointerException(); RunnableFuture ftask = newTaskFor(task); execute(ftask); return ftask; } protected RunnableFuture newTaskFor(Callable callable) { return new FutureTask (callable); }
java/util/concurrent/ThreadPoolExecutor.java
public void execute(Runnable command) { if (command == null) throw new NullPointerException(); /* * Proceed in 3 steps: * * 1. If fewer than corePoolSize threads are running, try to * start a new thread with the given command as its first * task. The call to addWorker atomically checks runState and * workerCount, and so prevents false alarms that would add * threads when it shouldn"t, by returning false. * * 2. If a task can be successfully queued, then we still need * to double-check whether we should have added a thread * (because existing ones died since last checking) or that * the pool shut down since entry into this method. So we * recheck state and if necessary roll back the enqueuing if * stopped, or start a new thread if there are none. * * 3. If we cannot queue task, then we try to add a new * thread. If it fails, we know we are shut down or saturated * and so reject the task. */ int c = ctl.get(); if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); } if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); if (! isRunning(recheck) && remove(command)) reject(command); else if (workerCountOf(recheck) == 0) addWorker(null, false); } else if (!addWorker(command, false)) reject(command); }
runWorker這里只是放入workQueue,然后判斷是否需要添加線程
java/util/concurrent/ThreadPoolExecutor.java
final void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null; w.unlock(); // allow interrupts boolean completedAbruptly = true; try { while (task != null || (task = getTask()) != null) { w.lock(); // If pool is stopping, ensure thread is interrupted; // if not, ensure thread is not interrupted. This // requires a recheck in second case to deal with // shutdownNow race while clearing interrupt if ((runStateAtLeast(ctl.get(), STOP) || (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))) && !wt.isInterrupted()) wt.interrupt(); try { beforeExecute(wt, task); Throwable thrown = null; try { task.run(); } catch (RuntimeException x) { thrown = x; throw x; } catch (Error x) { thrown = x; throw x; } catch (Throwable x) { thrown = x; throw new Error(x); } finally { afterExecute(task, thrown); } } finally { task = null; w.completedTasks++; w.unlock(); } } completedAbruptly = false; } finally { processWorkerExit(w, completedAbruptly); } }
futureTask.run這里循環從workQueue取出task,然后調用task.run()
java/util/concurrent/FutureTask.java
public void run() { if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())) return; try { Callablec = 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(result),而異常的話,會調用setException(ex)
protected void setException(Throwable t) { if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { outcome = t; UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state finishCompletion(); } } protected void set(V v) { if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { outcome = v; UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state finishCompletion(); } }
future.get(long)都把狀態從NEW設置為COMPLETING
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); }
這里看awaitDone,等待指定的時候,發現狀態不是COMPLETING,則拋出TimeoutException,讓調用線程返回。
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); } }
小結這里等待超時,然后返回原始狀態
由此可見,超時的機制其實不能中斷callable里頭實際執行的動作,超時只是讓調用線程能夠在指定時間返回而已,而底層調用的方法,實際還在執行。這里是需要額外注意的。
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/67850.html
摘要:主要的實現實際上運行還是一個,它對做了一個封裝,讓開發人員可以從其中獲取返回值是有狀態的共種狀態,四種狀態變換的可能和的區別通過方法調用有返回值可以拋異常結果的實現原理判斷狀態非狀態則直接進入返回結果處于狀態,則進入等待流程獲 主要的實現FutureTask # FutureTask實際上運行還是一個runnable,它對callable做了一個封裝,讓開發人員可以從其中獲取返回值; ...
摘要:零前期準備文章異常啰嗦且繞彎。版本版本簡介是中默認的實現類,常與結合進行多線程并發操作。所以方法的主體其實就是去喚醒被阻塞的線程。本文僅為個人的學習筆記,可能存在錯誤或者表述不清的地方,有緣補充 零 前期準備 0 FBI WARNING 文章異常啰嗦且繞彎。 1 版本 JDK 版本 : OpenJDK 11.0.1 IDE : idea 2018.3 2 ThreadLocal 簡介 ...
摘要:從而可以啟動和取消異步計算任務查詢異步計算任務是否完成和獲取異步計算任務的返回結果。原理分析在分析中我們沒有看它的父類,其中有一個方法,返回一個,說明該方法可以獲取異步任務的返回結果。 FutureTask介紹 FutureTask是一種可取消的異步計算任務。它實現了Future接口,代表了異步任務的返回結果。從而FutureTask可以啟動和取消異步計算任務、查詢異步計算任務是否完成...
摘要:可取消的異步計算。只有在計算完成后才能檢索結果如果計算還沒有完成,方法將會被阻塞。任務正常執行結束。任務執行過程中發生異常。任務即將被中斷。運行完成后將會清空。根據執行結果設置狀態。 FutureTask What is it ? 可取消的異步計算。該類提供了 Future的基本實現,其中包括啟動和取消計算的方法,查詢計算是否完成以及檢索計算結果的方法。只有在計算完成后才能檢索...
閱讀 1961·2021-09-09 09:33
閱讀 1107·2019-08-30 15:43
閱讀 2646·2019-08-30 13:45
閱讀 3297·2019-08-29 11:00
閱讀 845·2019-08-26 14:01
閱讀 3559·2019-08-26 13:24
閱讀 471·2019-08-26 11:56
閱讀 2683·2019-08-26 10:27