Tôi đã tình cờ gặp một vấn đề, có thể được tóm tắt như sau:Tại sao UncaughtExceptionHandler không được ExecutorService gọi?
Khi tôi tạo ra các chủ đề bằng tay (tức là bằng instantiating java.lang.Thread
) các UncaughtExceptionHandler
được gọi một cách thích hợp. Tuy nhiên, khi tôi sử dụng một số ExecutorService
với số ThreadFactory
, trình xử lý này được sử dụng. Tôi đã bỏ lỡ cái gì?
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.");
}
}
tôi mong đợi: Ba lần so với thông báo "của router ..."
tôi nhận: Thông điệp một lần (kích hoạt bởi các chủ đề được tạo thủ).
Sao chép bằng Java 1.6 trên Windows 7 và Mac OS X 10.5.
Có lẽ công việc này, đối với tôi đó là ok Nó không phải là một FixedThreadPool , nhưng SingleThreadPool ... nhưng bạn nhận được ý tưởng http://stackoverflow.com/a/44007121/8020889 –