我偶然發現了一個問題,可以總結如下:爲什麼ExecutorService不調用UncaughtExceptionHandler?
當我手動創建線程時(即通過實例化java.lang.Thread
),UncaughtExceptionHandler
被適當調用。但是,當我使用帶有ThreadFactory
的ExecutorService
時,處理程序被省略。我錯過了什麼?
public class ThreadStudy {
private static final int THREAD_POOL_SIZE = 1;
public static void main(String[] args) {
// create uncaught exception handler
final UncaughtExceptionHandler exceptionHandler = new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
synchronized (this) {
System.err.println("Uncaught exception in thread '" + t.getName() + "': " + e.getMessage());
}
}
};
// create thread factory
ThreadFactory threadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
// System.out.println("creating pooled thread");
final Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler(exceptionHandler);
return thread;
}
};
// create Threadpool
ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE, threadFactory);
// create Runnable
Runnable runnable = new Runnable() {
@Override
public void run() {
// System.out.println("A runnable runs...");
throw new RuntimeException("Error in Runnable");
}
};
// create Callable
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// System.out.println("A callable runs...");
throw new Exception("Error in Callable");
}
};
// a) submitting Runnable to threadpool
threadPool.submit(runnable);
// b) submit Callable to threadpool
threadPool.submit(callable);
// c) create a thread for runnable manually
final Thread thread_r = new Thread(runnable, "manually-created-thread");
thread_r.setUncaughtExceptionHandler(exceptionHandler);
thread_r.start();
threadPool.shutdown();
System.out.println("Done.");
}
}
我期望:消息的三倍「未捕獲異常...」
我得到:消息一次(由手動創建的線程觸發)。
在Windows 7和Mac OS X 10.5上使用Java 1.6重現。
也許這項工作,對我來說這是確定它是不是一個FixedThreadPool ,但SingleThreadPool ...但你明白http://stackoverflow.com/a/44007121/8020889 – 2017-05-16 16:48:39