線程池中線程拋了異常,該如何處理?
在實(shí)際開發(fā)中,我們常常會(huì)用到線程池,但任務(wù)一旦提交到線程池之后,如果發(fā)生異常之后,怎么處理? 怎么獲取到異常信息?在了解這個(gè)問題之前,可以先看一下 線程池的源碼解析,從源碼中我們知道了線程池的提交方式:submit和execute的區(qū)別,接下來分別使用他們執(zhí)行帶有異常的任務(wù)!看結(jié)果是怎么樣的!
我們先用偽代碼模擬一下線程池拋異常的場景:
public class ThreadPoolException {
public static void main(String[] args) {
//創(chuàng)建一個(gè)線程池
ExecutorService executorService= Executors.newFixedThreadPool(1);
//當(dāng)線程池拋出異常后 submit無提示,其他線程繼續(xù)執(zhí)行
executorService.submit(new task());
//當(dāng)線程池拋出異常后 execute拋出異常,其他線程繼續(xù)執(zhí)行新任務(wù)
executorService.execute(new task());
}
}
//任務(wù)類
class task implements Runnable{
@Override
public void run() {
System.out.println("進(jìn)入了task方法?。?!");
int i=1/0;
}
}
運(yùn)行結(jié)果:
圖片
可以看到:submit不打印異常信息,而execute則會(huì)打印異常信息!,submit的方式不打印異常信息,顯然在生產(chǎn)中,是不可行的,因?yàn)槲覀儫o法保證線程中的任務(wù)永不異常,而如果使用submit的方式出現(xiàn)了異常,直接如上寫法,我們將無法獲取到異常信息,做出對應(yīng)的判斷和處理,所以下一步需要知道如何獲取線程池拋出的異常!
推薦Java工程師技術(shù)指南:https://github.com/chenjiabing666/JavaFamily
submit()想要獲取異常信息就必須使用get()方法??!
//當(dāng)線程池拋出異常后 submit無提示,其他線程繼續(xù)執(zhí)行
Future<?> submit = executorService.submit(new task());
submit.get();
submit打印異常信息如下:
圖片
方案一:使用 try -catch
public class ThreadPoolException {
public static void main(String[] args) {
//創(chuàng)建一個(gè)線程池
ExecutorService executorService = Executors.newFixedThreadPool(1);
//當(dāng)線程池拋出異常后 submit無提示,其他線程繼續(xù)執(zhí)行
executorService.submit(new task());
//當(dāng)線程池拋出異常后 execute拋出異常,其他線程繼續(xù)執(zhí)行新任務(wù)
executorService.execute(new task());
}
}
// 任務(wù)類
class task implements Runnable {
@Override
public void run() {
try {
System.out.println("進(jìn)入了task方法?。?!");
int i = 1 / 0;
} catch (Exception e) {
System.out.println("使用了try -catch 捕獲異常" + e);
}
}
}
打印結(jié)果:
圖片
可以看到 submit 和 execute都清晰易懂的捕獲到了異常,可以知道我們的任務(wù)出現(xiàn)了問題,而不是消失的無影無蹤。關(guān)注公眾號:碼猿技術(shù)專欄,回復(fù)關(guān)鍵詞:1111 獲取阿里內(nèi)部Java性能調(diào)優(yōu)手冊!
方案二:使用Thread.setDefaultUncaughtExceptionHandler方法捕獲異常
方案一中,每一個(gè)任務(wù)都要加一個(gè)try-catch 實(shí)在是太麻煩了,而且代碼也不好看,那么這樣想的話,可以用Thread.setDefaultUncaughtExceptionHandler方法捕獲異常
圖片
UncaughtExceptionHandler 是Thread類一個(gè)內(nèi)部類,也是一個(gè)函數(shù)式接口。
推薦Java工程師技術(shù)指南:https://github.com/chenjiabing666/JavaFamily
內(nèi)部的uncaughtException是一個(gè)處理線程內(nèi)發(fā)生的異常的方法,參數(shù)為線程對象t和異常對象e。
圖片
應(yīng)用在線程池中如下所示:重寫它的線程工廠方法,在線程工廠創(chuàng)建線程的時(shí)候,都賦予UncaughtExceptionHandler處理器對象。
public class ThreadPoolException {
public static void main(String[] args) throws InterruptedException {
//1.實(shí)現(xiàn)一個(gè)自己的線程池工廠
ThreadFactory factory = (Runnable r) -> {
//創(chuàng)建一個(gè)線程
Thread t = new Thread(r);
//給創(chuàng)建的線程設(shè)置UncaughtExceptionHandler對象 里面實(shí)現(xiàn)異常的默認(rèn)邏輯
t.setDefaultUncaughtExceptionHandler((Thread thread1, Throwable e) -> {
System.out.println("線程工廠設(shè)置的exceptionHandler" + e.getMessage());
});
return t;
};
//2.創(chuàng)建一個(gè)自己定義的線程池,使用自己定義的線程工廠
ExecutorService executorService = new ThreadPoolExecutor(
1,
1,
0,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue(10),
factory);
// submit無提示
executorService.submit(new task());
Thread.sleep(1000);
System.out.println("==================為檢驗(yàn)打印結(jié)果,1秒后執(zhí)行execute方法");
// execute 方法被線程工廠factory 的UncaughtExceptionHandler捕捉到異常
executorService.execute(new task());
}
}
class task implements Runnable {
@Override
public void run() {
System.out.println("進(jìn)入了task方法?。?!");
int i = 1 / 0;
}
}
打印結(jié)果如下:
圖片
根據(jù)打印結(jié)果我們看到,execute方法被線程工廠factory中設(shè)置的 UncaughtExceptionHandler捕捉到異常,而submit方法卻沒有任何反應(yīng)!說明UncaughtExceptionHandler在submit中并沒有被調(diào)用。這是為什么呢?
在日常使用中,我們知道,execute和submit最大的區(qū)別就是execute沒有返回值,submit有返回值。submit返回的是一個(gè)future ,可以通過這個(gè)future取到線程執(zhí)行的結(jié)果或者異常信息。
Future<?> submit = executorService.submit(new task());
//打印異常結(jié)果
System.out.println(submit.get());
圖片
從結(jié)果看出:submit并不是丟失了異常,使用future.get()還是有異常打印的??!那為什么線程工廠factory 的UncaughtExceptionHandler沒有打印異常呢?猜測是submit方法內(nèi)部已經(jīng)捕獲了異常, 只是沒有打印出來,也因?yàn)楫惓R呀?jīng)被捕獲,因此jvm也就不會(huì)去調(diào)用Thread的UncaughtExceptionHandler去處理異常。
接下來,驗(yàn)證猜想:
首先看一下submit和execute的源碼:
execute方法的源碼在這博客中寫的很詳細(xì),點(diǎn)擊查看execute源碼,在此就不再啰嗦了
https://blog.csdn.net/qq_45076180/article/details/108316340
submit源碼在底層還是調(diào)用的execute方法,只不過多一層Future封裝,并返回了這個(gè)Future,這也解釋了為什么submit會(huì)有返回值
//submit()方法
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
//execute內(nèi)部執(zhí)行這個(gè)對象內(nèi)部的邏輯,然后將結(jié)果或者異常 set到這個(gè)ftask里面
RunnableFuture<T> ftask = newTaskFor(task);
// 執(zhí)行execute方法
execute(ftask);
//返回這個(gè)ftask
return ftask;
}
可以看到submit也是調(diào)用的execute,在execute方法中,我們的任務(wù)被提交到了addWorker(command, true) ,然后為每一個(gè)任務(wù)創(chuàng)建一個(gè)Worker去處理這個(gè)線程,這個(gè)Worker也是一個(gè)線程,執(zhí)行任務(wù)時(shí)調(diào)用的就是Worker的run方法!run方法內(nèi)部又調(diào)用了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 {
//這里就是線程可以重用的原因,循環(huán)+條件判斷,不斷從隊(duì)列中取任務(wù)
//還有一個(gè)問題就是非核心線程的超時(shí)刪除是怎么解決的
//主要就是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 {
//執(zhí)行線程
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();
}
}
//出現(xiàn)異常時(shí)completedAbruptly不會(huì)被修改為false
completedAbruptly = false;
} finally {
//如果如果completedAbruptly值為true,則出現(xiàn)異常,則添加新的Worker處理后邊的線程
processWorkerExit(w, completedAbruptly);
}
}
核心就在 task.run(); 這個(gè)方法里面了, 期間如果發(fā)生異常會(huì)被拋出。
- 如果用execute提交的任務(wù),會(huì)被封裝成了一個(gè)runable任務(wù),然后進(jìn)去 再被封裝成一個(gè)worker,最后在worker的run方法里面調(diào)用runWoker方法, runWoker方法里面執(zhí)行任務(wù)任務(wù),如果任務(wù)出現(xiàn)異常,用try-catch捕獲異常往外面拋,我們在最外層使用try-catch捕獲到了 runWoker方法中拋出的異常。因此我們在execute中看到了我們的任務(wù)的異常信息。
- 那么為什么submit沒有異常信息呢? 因?yàn)閟ubmit是將任務(wù)封裝成了一個(gè)futureTask ,然后這個(gè)futureTask被封裝成worker,在woker的run方法里面,最終調(diào)用的是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;
//在此方法中設(shè)置了異常信息
setException(ex);
}
if (ran)
set(result);
}
//省略下文
。。。。。。
setException(ex)`方法如下:將異常對象賦予`outcome
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//將異常對象賦予outcome,記住這個(gè)outcome,
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
將異常對象賦予outcome有什么用呢?這個(gè)outcome是什么呢?當(dāng)我們使用submit返回Future對象,并使用Future.get()時(shí), 會(huì)調(diào)用內(nèi)部的report方法!
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
//注意這個(gè)方法
return report(s);
}
reoport里面實(shí)際上返回的是outcome ,剛好之前的異常就set到了這個(gè)outcome里面
private V report(int s) throws ExecutionException {
//設(shè)置`outcome`
Object x = outcome;
if (s == NORMAL)
//返回`outcome`
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}
因此,在用submit提交的時(shí)候,runable對象被封裝成了future ,future 里面的 run方法在處理異常時(shí), try-catch了所有的異常,通過setException(ex);方法設(shè)置到了變量outcome里面, 可以通過future.get獲取到outcome。
所以在submit提交的時(shí)候,里面發(fā)生了異常, 是不會(huì)有任何拋出信息的。而通過future.get()可以獲取到submit拋出的異常!在submit里面,除了從返回結(jié)果里面取到異常之外, 沒有其他方法。因此,在不需要返回結(jié)果的情況下,最好用execute ,這樣就算沒有寫try-catch,疏漏了異常捕捉,也不至于丟掉異常信息。
方案三:重寫afterExecute進(jìn)行異常處理
通過上述源碼分析,在excute的方法里面,可以通過重寫afterExecute進(jìn)行異常處理,但是注意! 這個(gè)也只適用于excute提交(submit的方式比較麻煩,下面說),因?yàn)閟ubmit的task.run里面把異常吞了,根本不會(huì)跑出來異常,因此也不會(huì)有異常進(jìn)入到afterExecute里面。
在runWorker里面,調(diào)用task.run之后,會(huì)調(diào)用線程池的 afterExecute(task, thrown) 方法
final void runWorker(Worker w) {
//當(dāng)前線程
Thread wt = Thread.currentThread();
//我們的提交的任務(wù)
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 {
//直接就調(diào)用了task的run方法
task.run(); //如果是futuretask的run,里面是吞掉了異常,不會(huì)有異常拋出,
// 因此Throwable thrown = null; 也不會(huì)進(jìn)入到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 {
//調(diào)用線程池的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.創(chuàng)建一個(gè)自己定義的線程池
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());
}
};
//當(dāng)線程池拋出異常后 execute
executorService.execute(new task());
}
}
class task3 implements Runnable {
@Override
public void run() {
System.out.println("進(jìn)入了task方法?。。?);
int i = 1 / 0;
}
}
執(zhí)行結(jié)果:我們可以在afterExecute方法內(nèi)部對異常進(jìn)行處理
如果要用這個(gè)afterExecute處理submit提交的異常, 要額外處理。判斷Throwable是否是FutureTask,如果是代表是submit提交的異常,代碼如下:
public class ThreadPoolException3 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//1.創(chuàng)建一個(gè)自己定義的線程池
ExecutorService executorService = new ThreadPoolExecutor(
2,
3,
0,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue(10)
) {
//重寫afterExecute方法
@Override
protected void afterExecute(Runnable r, Throwable t) {
//這個(gè)是excute提交的時(shí)候
if (t != null) {
System.out.println("afterExecute里面獲取到excute提交的異常信息,處理異常" + t.getMessage());
}
//如果r的實(shí)際類型是FutureTask 那么是submit提交的,所以可以在里面get到異常
if (r instanceof FutureTask) {
try {
Future<?> future = (Future<?>) r;
//get獲取異常
future.get();
} catch (Exception e) {
System.out.println("afterExecute里面獲取到submit提交的異常信息,處理異常" + e);
}
}
}
};
//當(dāng)線程池拋出異常后 execute
executorService.execute(new task());
//當(dāng)線程池拋出異常后 submit
executorService.submit(new task());
}
}
class task3 implements Runnable {
@Override
public void run() {
System.out.println("進(jìn)入了task方法!?。?);
int i = 1 / 0;
}
}
處理結(jié)果如下:
圖片
可以看到使用重寫afterExecute這種方式,既可以處理execute拋出的異常,也可以處理submit拋出的異常