執行緒出現異常測試
private int i;
public Task(int i) {
this.i = i;
}
@Override
public void run() {
if (i == 5) {
//System.out.println("throw exception");
throw new IllegalArgumentException();
System.out.println(i);
如果i==5,將丟擲一個異常
public class TestTask {
public static void main(String[] args) {
int i = 0;
while (true) {
if (i == 10) break;
try {
new Thread(new Task(i++)).start();
} catch (Exception e) {
System.out.println("catch exception...");
透過使用try-catch,嘗試對丟擲的異常進行捕獲
Connected to the target VM, address: "127.0.0.1:64551", transport: "socket"
0
1
2
3
4
6
7
8
9
Exception in thread "pool-1-thread-1" java.lang.IllegalArgumentException
at com.h2t.study.thread.Task.run(Task.java:21)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
異常沒有被捕獲,只是在控制檯列印了異常,並且不影響後續任務的執行 emmmm這是為什麼呢,捕獲不到異常就不知道程式出錯了,到時候哪天有個任務不正常排查都排查不到,這樣是要不得的。看一下Thread這個類,有個叫dispatchUncaughtException的方法,作用如其名,分發未捕獲的異常,把這段程式碼揪出來:Thread#dispatchUncaughtException
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
find usage是找不到該方法在哪裡呼叫的,因為這個方法只被JVM呼叫 Thread#getUncaughtExceptionHandler: 獲取UncaughtExceptionHandler介面實現類
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
UncaughtExceptionHandler是Thread中定義的介面,在Thread類中uncaughtExceptionHandler預設是null,因此該方法將返回group,即實現了UncaughtExceptionHandler介面的ThreadGroup類 UncaughtExceptionHandler#uncaughtException: ThreadGroup類的uncaughtException方法實現
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
因為在Thread類中沒有對group【parent】和defaultUncaughtExceptionHandler【Thread.getDefaultUncaughtExceptionHandler】進行賦值,因此將進入最後一層條件,將異常列印到控制檯中,對異常不做任何處理。 整個異常處理器呼叫鏈如下:
首先判斷預設異常處理器【defaultUncaughtExceptionHandler】是不是為null,在判斷執行緒組異常處理器【group】是不是為null,在判斷自定義異常處理器【uncaughtExceptionHandler】是不是為null,都為null則在控制檯列印異常
分析了一下原始碼就知道如果想對任務執行過程中的異常進行處理一個就是讓ThreadGroup不為null,另外一種思路就是讓UncaughtExceptionHandler型別的變數值不為null。
private static class ExceptionHandler implements Thread.UncaughtExceptionHandler {
System.out.println("異常捕獲到了:" + e);
Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.out.println("異常捕獲到 了: " + e));
Thread thread = new Thread(new Task(i++));
thread.start();
列印結果:
異常捕獲到了:java.lang.IllegalArgumentException
透過設定預設異常就不需要為每個執行緒都設定一次了
Thread t = new Thread(new Task(i++));
t.setUncaughtExceptionHandler(new ExceptionHandler());
MyThreadGroup myThreadGroup = new MyThreadGroup("測試執行緒執行緒組");
Thread t = new Thread(myThreadGroup, new Task(i++))
自定義執行緒組:MyThreadGroup.java
private static class MyThreadGroup extends ThreadGroup {
public MyThreadGroup(String name) {
super(name);
System.out.println("捕獲到異常了:" + e);
捕獲到異常了:java.lang.IllegalArgumentException
執行緒組異常捕獲處理器很適合為執行緒進行分組處理的場景,每個分組出現異常的處理方式不相同 設定完異常處理器後異常都能被捕獲了,但是不知道為什麼設定異常處理器後任務的執行順序亂了,難道是因為為每個執行緒設定異常處理器的時間不同【想不通】
一般應用中執行緒都是透過執行緒池建立複用的,因此對執行緒池的異常處理就是為執行緒池工廠類【ThreadFactory實現類】生成的執行緒新增異常處理器
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new Task(i++))
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
threadPoolExecutor.setThreadFactory(new MyThreadFactory());
threadPoolExecutor.execute(new Task(i++));
自定義工廠類:
MyThreadFactory.java
private static class MyThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread t = new Thread();
//自定義UncaughtExceptionHandler
return t;
來自JVM的設計理念"執行緒是獨立執行的程式碼片斷,執行緒的問題應該由執行緒自己來解決,而不要委託到外部"。因此在Java中,執行緒方法的異常【即任務丟擲的異常】,應該線上程程式碼邊界之內處理掉,而不應該線上程方法外面由其他執行緒處理
前面介紹的是執行緒執行Runnable型別任務的情況,眾所周知,還有一種有返回值的Callable任務型別 測試程式碼:
TestTask.java
FutureTask<Integer> task = new FutureTask<>(new CallableTask(i++));
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
Disconnected from the target VM, address: "127.0.0.1:64936", transport: "socket"
觀察結果,異常沒有被捕獲,thread.setUncaughtExceptionHandler(new ExceptionHandler())方法設定無效,emmmmm,這又是為什麼呢,在問為什麼就是十萬個為什麼兒童了。檢視FutureTask的run方法,FutureTask#run:
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
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);
FutureTask#setException:
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//將異常設定給outcome變數
outcome = t;
//設定任務的狀態為EXCEPTIONAL
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
看到catch這段程式碼,當執行任務捕獲到異常的時候,會將任務的處理結果設定為null,並且呼叫setException方法對捕獲的異常進行處理,因為setUncaughtExceptionHandler只對未捕獲的異常進行處理,FutureTask已經對異常進行了捕獲處理,因此呼叫setUncaughtExceptionHandler捕獲異常無效 對任務的執行結果呼叫get方法:
//列印結果
System.out.println(task.get());
System.out.println("異常被抓住了, e: " + e);
執行結果將會將捕獲到的異常打印出來,執行結果:
異常被抓住了, e: java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException
Disconnected from the target VM, address: "127.0.0.1:50900", transport: "socket"
FutureTask#get:
public V get() throws InterruptedException, ExecutionException {
if (s <= COMPLETING)
//未完成等待任務執行完成
s = awaitDone(false, 0L);
return report(s);
FutureTask#report:
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);
outcome在setException方法中被設定為了異常,並且s為state的狀態最終8被設定為EXCEPTIONAL,因此方法將捕獲的任務丟擲【new ExecutionException((Throwable)x)】
Callable任務丟擲的異常能在程式碼中透過try-catch捕獲到,但是隻有呼叫get方法後才能捕獲到
執行緒出現異常測試
任務類:Task.javapublic class Task implements Runnable {private int i;
public Task(int i) {
this.i = i;
}
@Override
public void run() {
if (i == 5) {
//System.out.println("throw exception");
throw new IllegalArgumentException();
}
System.out.println(i);
}
}
如果i==5,將丟擲一個異常
執行緒測試類:TaskTest.javapublic class TestTask {
public static void main(String[] args) {
int i = 0;
while (true) {
if (i == 10) break;
try {
new Thread(new Task(i++)).start();
} catch (Exception e) {
System.out.println("catch exception...");
}
}
}
}
透過使用try-catch,嘗試對丟擲的異常進行捕獲
測試結果Connected to the target VM, address: "127.0.0.1:64551", transport: "socket"
0
1
2
3
4
6
7
8
9
Exception in thread "pool-1-thread-1" java.lang.IllegalArgumentException
at com.h2t.study.thread.Task.run(Task.java:21)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
異常沒有被捕獲,只是在控制檯列印了異常,並且不影響後續任務的執行 emmmm這是為什麼呢,捕獲不到異常就不知道程式出錯了,到時候哪天有個任務不正常排查都排查不到,這樣是要不得的。看一下Thread這個類,有個叫dispatchUncaughtException的方法,作用如其名,分發未捕獲的異常,把這段程式碼揪出來:Thread#dispatchUncaughtException
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
find usage是找不到該方法在哪裡呼叫的,因為這個方法只被JVM呼叫 Thread#getUncaughtExceptionHandler: 獲取UncaughtExceptionHandler介面實現類
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
}
UncaughtExceptionHandler是Thread中定義的介面,在Thread類中uncaughtExceptionHandler預設是null,因此該方法將返回group,即實現了UncaughtExceptionHandler介面的ThreadGroup類 UncaughtExceptionHandler#uncaughtException: ThreadGroup類的uncaughtException方法實現
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}
因為在Thread類中沒有對group【parent】和defaultUncaughtExceptionHandler【Thread.getDefaultUncaughtExceptionHandler】進行賦值,因此將進入最後一層條件,將異常列印到控制檯中,對異常不做任何處理。 整個異常處理器呼叫鏈如下:
首先判斷預設異常處理器【defaultUncaughtExceptionHandler】是不是為null,在判斷執行緒組異常處理器【group】是不是為null,在判斷自定義異常處理器【uncaughtExceptionHandler】是不是為null,都為null則在控制檯列印異常
執行緒異常處理分析了一下原始碼就知道如果想對任務執行過程中的異常進行處理一個就是讓ThreadGroup不為null,另外一種思路就是讓UncaughtExceptionHandler型別的變數值不為null。
異常處理器:ExceptionHandler.javaprivate static class ExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("異常捕獲到了:" + e);
}
}
設定預設異常處理器Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.out.println("異常捕獲到 了: " + e));
int i = 0;
while (true) {
if (i == 10) break;
Thread thread = new Thread(new Task(i++));
thread.start();
}
列印結果:
0
2
1
3
9
6
7
4
異常捕獲到了:java.lang.IllegalArgumentException
8
透過設定預設異常就不需要為每個執行緒都設定一次了
設定自定義異常處理器Thread t = new Thread(new Task(i++));
t.setUncaughtExceptionHandler(new ExceptionHandler());
列印結果:
0
2
4
異常捕獲到了:java.lang.IllegalArgumentException
6
1
3
7
9
8
設定執行緒組異常處理器MyThreadGroup myThreadGroup = new MyThreadGroup("測試執行緒執行緒組");
Thread t = new Thread(myThreadGroup, new Task(i++))
自定義執行緒組:MyThreadGroup.java
private static class MyThreadGroup extends ThreadGroup {
public MyThreadGroup(String name) {
super(name);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("捕獲到異常了:" + e);
}
}
列印結果:
1
2
0
4
3
6
7
8
9
捕獲到異常了:java.lang.IllegalArgumentException
執行緒組異常捕獲處理器很適合為執行緒進行分組處理的場景,每個分組出現異常的處理方式不相同 設定完異常處理器後異常都能被捕獲了,但是不知道為什麼設定異常處理器後任務的執行順序亂了,難道是因為為每個執行緒設定異常處理器的時間不同【想不通】
執行緒池異常處理一般應用中執行緒都是透過執行緒池建立複用的,因此對執行緒池的異常處理就是為執行緒池工廠類【ThreadFactory實現類】生成的執行緒新增異常處理器
預設異常處理器Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new Task(i++))
自定義異常處理器ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
threadPoolExecutor.setThreadFactory(new MyThreadFactory());
threadPoolExecutor.execute(new Task(i++));
自定義工廠類:
MyThreadFactory.java
private static class MyThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread();
//自定義UncaughtExceptionHandler
t.setUncaughtExceptionHandler(new ExceptionHandler());
return t;
}
}
設計原則,為什麼要由執行緒自身進行捕獲來自JVM的設計理念"執行緒是獨立執行的程式碼片斷,執行緒的問題應該由執行緒自己來解決,而不要委託到外部"。因此在Java中,執行緒方法的異常【即任務丟擲的異常】,應該線上程程式碼邊界之內處理掉,而不應該線上程方法外面由其他執行緒處理
執行緒執行Callable任務前面介紹的是執行緒執行Runnable型別任務的情況,眾所周知,還有一種有返回值的Callable任務型別 測試程式碼:
TestTask.java
public class TestTask {
public static void main(String[] args) {
int i = 0;
while (true) {
if (i == 10) break;
FutureTask<Integer> task = new FutureTask<>(new CallableTask(i++));
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
}
}
private static class ExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("異常捕獲到了:" + e);
}
}
}
列印結果:
Disconnected from the target VM, address: "127.0.0.1:64936", transport: "socket"
0
1
2
3
4
6
7
8
9
觀察結果,異常沒有被捕獲,thread.setUncaughtExceptionHandler(new ExceptionHandler())方法設定無效,emmmmm,這又是為什麼呢,在問為什麼就是十萬個為什麼兒童了。檢視FutureTask的run方法,FutureTask#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);
}
}
FutureTask#setException:
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//將異常設定給outcome變數
outcome = t;
//設定任務的狀態為EXCEPTIONAL
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
看到catch這段程式碼,當執行任務捕獲到異常的時候,會將任務的處理結果設定為null,並且呼叫setException方法對捕獲的異常進行處理,因為setUncaughtExceptionHandler只對未捕獲的異常進行處理,FutureTask已經對異常進行了捕獲處理,因此呼叫setUncaughtExceptionHandler捕獲異常無效 對任務的執行結果呼叫get方法:
int i = 0;
while (true) {
if (i == 10) break;
FutureTask<Integer> task = new FutureTask<>(new CallableTask(i++));
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
//列印結果
try {
System.out.println(task.get());
} catch (Exception e) {
System.out.println("異常被抓住了, e: " + e);
}
}
執行結果將會將捕獲到的異常打印出來,執行結果:
0
1
2
3
4
異常被抓住了, e: java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException
6
7
Disconnected from the target VM, address: "127.0.0.1:50900", transport: "socket"
8
9
FutureTask#get:
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
//未完成等待任務執行完成
s = awaitDone(false, 0L);
return report(s);
}
FutureTask#report:
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);
}
outcome在setException方法中被設定為了異常,並且s為state的狀態最終8被設定為EXCEPTIONAL,因此方法將捕獲的任務丟擲【new ExecutionException((Throwable)x)】
總結:Callable任務丟擲的異常能在程式碼中透過try-catch捕獲到,但是隻有呼叫get方法後才能捕獲到