在實際開發中,我們常常會用到線程池,但任務一旦提交到線程池之後,如果發生異常之後,怎麼處理? 怎麼獲取到異常信息?
在瞭解這個問題之前,可以先看一下 線程池的源碼解析,從源碼中我們知道了線程池的提交方式:submit和execute的區別,接下來分別使用他們執行帶有異常的任務!看結果是怎麼樣的!
我們先用僞代碼模擬一下線程池拋異常的場景:
public class ThreadPoolException {
public static void main(String[] args) {
//創建一個線程池
ExecutorService executorService= Executors.newFixedThreadPool(1);
//當線程池拋出異常後 submit無提示,其他線程繼續執行
executorService.submit(new task());
//當線程池拋出異常後 execute拋出異常,其他線程繼續執行新任務
executorService.execute(new task());
}
}
//任務類
class task implements Runnable{
@Override
public void run() {
System.out.println("進入了task方法!!!");
int i=1/0;
}
}
運行結果:
可以看到:submit不打印異常信息,而execute則會打印異常信息!,submit的方式不打印異常信息,顯然在生產中,是不可行的,因爲我們無法保證線程中的任務永不異常,而如果使用submit的方式出現了異常,直接如上寫法,我們將無法獲取到異常信息,做出對應的判斷和處理,所以下一步需要知道如何獲取線程池拋出的異常!
submit()
想要獲取異常信息就必須使用get()
方法!!
//當線程池拋出異常後 submit無提示,其他線程繼續執行
Future<?> submit = executorService.submit(new task());
submit.get();
submit打印異常信息如下:
推薦一個開源免費的 Spring Boot 最全教程:
方案一
使用
try -catch
public class ThreadPoolException {
public static void main(String[] args) {
//創建一個線程池
ExecutorService executorService = Executors.newFixedThreadPool(1);
//當線程池拋出異常後 submit無提示,其他線程繼續執行
executorService.submit(new task());
//當線程池拋出異常後 execute拋出異常,其他線程繼續執行新任務
executorService.execute(new task());
}
}
// 任務類
class task implements Runnable {
@Override
public void run() {
try {
System.out.println("進入了task方法!!!");
int i = 1 / 0;
} catch (Exception e) {
System.out.println("使用了try -catch 捕獲異常" + e);
}
}
}
打印結果:
可以看到 submit 和 execute都清晰易懂的捕獲到了異常,可以知道我們的任務出現了問題,而不是消失的無影無蹤。
方案二:
使用
Thread.setDefaultUncaughtExceptionHandler
方法捕獲異常。
方案一中,每一個任務都要加一個try-catch
實在是太麻煩了,而且代碼也不好看,那麼這樣想的話,可以用Thread.setDefaultUncaughtExceptionHandler
方法捕獲異常
UncaughtExceptionHandler
是Thread類一個內部類,也是一個函數式接口。
內部的uncaughtException
是一個處理線程內發生的異常的方法,參數爲線程對象t和異常對象e。
應用在線程池中如下所示:重寫它的線程工廠方法,在線程工廠創建線程的時候,都賦予UncaughtExceptionHandler
處理器對象。
public class ThreadPoolException {
public static void main(String[] args) throws InterruptedException {
//1.實現一個自己的線程池工廠
ThreadFactory factory = (Runnable r) -> {
//創建一個線程
Thread t = new Thread(r);
//給創建的線程設置UncaughtExceptionHandler對象 裏面實現異常的默認邏輯
t.setDefaultUncaughtExceptionHandler((Thread thread1, Throwable e) -> {
System.out.println("線程工廠設置的exceptionHandler" + e.getMessage());
});
return t;
};
//2.創建一個自己定義的線程池,使用自己定義的線程工廠
ExecutorService executorService = new ThreadPoolExecutor(
1,
1,
0,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue(10),
factory);
// submit無提示
executorService.submit(new task());
Thread.sleep(1000);
System.out.println("==================爲檢驗打印結果,1秒後執行execute方法");
// execute 方法被線程工廠factory 的UncaughtExceptionHandler捕捉到異常
executorService.execute(new task());
}
}
class task implements Runnable {
@Override
public void run() {
System.out.println("進入了task方法!!!");
int i = 1 / 0;
}
}
打印結果如下:
根據打印結果我們看到,execute方法被線程工廠factory中設置的 UncaughtExceptionHandler
捕捉到異常,而submit方法卻沒有任何反應!說明UncaughtExceptionHandler
在submit中並沒有被調用。這是爲什麼呢?
在日常使用中,我們知道,execute和submit最大的區別就是execute沒有返回值,submit有返回值。submit返回的是一個future ,可以通過這個future取到線程執行的結果或者異常信息。
Future<?> submit = executorService.submit(new task());
//打印異常結果
System.out.println(submit.get());
從結果看出:submit並不是丟失了異常,使用future.get()
還是有異常打印的!!那爲什麼線程工廠factory 的UncaughtExceptionHandler
沒有打印異常呢?猜測是submit方法內部已經捕獲了異常, 只是沒有打印出來,也因爲異常已經被捕獲,因此jvm也就不會去調用Thread的UncaughtExceptionHandler
去處理異常。
接下來,驗證猜想。submit源碼在底層還是調用的execute方法,只不過多一層Future封裝,並返回了這個Future,這也解釋了爲什麼submit會有返回值
//submit()方法
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
//execute內部執行這個對象內部的邏輯,然後將結果或者異常 set到這個ftask裏面
RunnableFuture<T> ftask = newTaskFor(task);
// 執行execute方法
execute(ftask);
//返回這個ftask
return ftask;
}
可以看到submit也是調用的execute,在execute方法中,我們的任務被提交到了addWorker(command, true)
,然後爲每一個任務創建一個Worker去處理這個線程,這個Worker也是一個線程,執行任務時調用的就是Worker的run方法!run方法內部又調用了runworker方法!如下所示:
public void run() {
runWorker(this);
}
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//這裏就是線程可以重用的原因,循環+條件判斷,不斷從隊列中取任務
//還有一個問題就是非核心線程的超時刪除是怎麼解決的
//主要就是getTask方法()見下文③
while (task != null || (task = getTask()) != null) {
w.lock();
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 {
//execute的方式可以重寫此方法處理異常
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
//出現異常時completedAbruptly不會被修改爲false
completedAbruptly = false;
} finally {
//如果如果completedAbruptly值爲true,則出現異常,則添加新的Worker處理後邊的線程
processWorkerExit(w, completedAbruptly);
}
}
核心就在 task.run();
這個方法裏面了, 期間如果發生異常會被拋出。
- 如果用execute提交的任務,會被封裝成了一個runable任務,然後進去 再被封裝成一個worker,最後在worker的run方法裏面調用runWoker方法,
runWoker
方法裏面執行任務任務,如果任務出現異常,用try-catch
捕獲異常往外面拋,我們在最外層使用try-catch
捕獲到了runWoker
方法中拋出的異常。因此我們在execute中看到了我們的任務的異常信息。 - 那麼爲什麼submit沒有異常信息呢? 因爲submit是將任務封裝成了一個
futureTask
,然後這個futureTask
被封裝成worker,在woker的run方法裏面,最終調用的是futureTask
的run方法, 猜測裏面是直接吞掉了異常,並沒有拋出異常,因此在worker的runWorker
方法裏面無法捕獲到異常。
下面來看一下futureTask
的run方法,果不其然,在try-catch中吞掉了異常,將異常放到了 setException(ex);
裏面
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);
}
//省略下文
。。。。。。
setException(ex)`方法如下:將異常對象賦予`outcome
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//將異常對象賦予outcome,記住這個outcome,
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
將異常對象賦予outcome
有什麼用呢?這個outcome
是什麼呢?當我們使用submit返回Future對象,並使用Future.get()
時, 會調用內部的report方法!
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
//注意這個方法
return report(s);
}
reoport裏面實際上返回的是outcome ,剛好之前的異常就set到了這個outcome裏面
private V report(int s) throws ExecutionException {
//設置`outcome`
Object x = outcome;
if (s == NORMAL)
//返回`outcome`
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}
因此,在用submit提交的時候,runable對象被封裝成了future ,future 裏面的 run方法在處理異常時, try-catch
了所有的異常,通過setException(ex);
方法設置到了變量outcome裏面, 可以通過future.get
獲取到outcome。
所以在submit提交的時候,裏面發生了異常, 是不會有任何拋出信息的。而通過future.get()
可以獲取到submit拋出的異常!在submit裏面,除了從返回結果裏面取到異常之外, 沒有其他方法。因此,在不需要返回結果的情況下,最好用execute ,這樣就算沒有寫try-catch
,疏漏了異常捕捉,也不至於丟掉異常信息。
方案三
重寫afterExecute進行異常處理。
通過上述源碼分析,在excute的方法裏面,可以通過重寫afterExecute
進行異常處理,但是注意! 這個也只適用於excute提交(submit的方式比較麻煩,下面說),因爲submit的task.run
裏面把異常吞了,根本不會跑出來異常,因此也不會有異常進入到afterExecute
裏面。
在runWorker
裏面,調用task.run之後,會調用線程池的 afterExecute(task, thrown)
方法
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 ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
//直接就調用了task的run方法
task.run(); //如果是futuretask的run,裏面是吞掉了異常,不會有異常拋出,
// 因此Throwable thrown = null; 也不會進入到catch裏面
} 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和異常
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
重寫afterExecute
處理execute提交的異常
public class ThreadPoolException3 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//1.創建一個自己定義的線程池
ExecutorService executorService = new ThreadPoolExecutor(
2,
3,
0,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue(10)
) {
//重寫afterExecute方法
@Override
protected void afterExecute(Runnable r, Throwable t) {
System.out.println("afterExecute裏面獲取到異常信息,處理異常" + t.getMessage());
}
};
//當線程池拋出異常後 execute
executorService.execute(new task());
}
}
class task3 implements Runnable {
@Override
public void run() {
System.out.println("進入了task方法!!!");
int i = 1 / 0;
}
}
執行結果:我們可以在afterExecute
方法內部對異常進行處理
如果要用這個afterExecute
處理submit提交的異常, 要額外處理。判斷Throwable
是否是FutureTask
,如果是代表是submit提交的異常,代碼如下:
public class ThreadPoolException3 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//1.創建一個自己定義的線程池
ExecutorService executorService = new ThreadPoolExecutor(
2,
3,
0,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue(10)
) {
//重寫afterExecute方法
@Override
protected void afterExecute(Runnable r, Throwable t) {
//這個是excute提交的時候
if (t != null) {
System.out.println("afterExecute裏面獲取到excute提交的異常信息,處理異常" + t.getMessage());
}
//如果r的實際類型是FutureTask 那麼是submit提交的,所以可以在裏面get到異常
if (r instanceof FutureTask) {
try {
Future<?> future = (Future<?>) r;
//get獲取異常
future.get();
} catch (Exception e) {
System.out.println("afterExecute裏面獲取到submit提交的異常信息,處理異常" + e);
}
}
}
};
//當線程池拋出異常後 execute
executorService.execute(new task());
//當線程池拋出異常後 submit
executorService.submit(new task());
}
}
class task3 implements Runnable {
@Override
public void run() {
System.out.println("進入了task方法!!!");
int i = 1 / 0;
}
}
處理結果如下:
可以看到使用重寫afterExecute
這種方式,既可以處理execute拋出的異常,也可以處理submit拋出的異常。
版權聲明:本文爲CSDN博主「知識分子_」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。原文鏈接:https://blog.csdn.net/qq_45076180/article/details/114552567
近期熱文推薦:
1.1,000+ 道 Java面試題及答案整理(2022最新版)
4.別再寫滿屏的爆爆爆炸類了,試試裝飾器模式,這纔是優雅的方式!!
覺得不錯,別忘了隨手點贊+轉發哦!