ThreadPools中的异常处理 [英] Exception handling in ThreadPools
问题描述
我有一个ScheduledThreadPoolExecutor,似乎正在吃异常。如果提交的Runnable抛出异常,我想要我的执行者服务通知我。
I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
例如,我想要下面的代码至少打印出IndexArrayOutOfBoundsException的stackTrace
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
作为一个问题。有没有办法为ScheduledThreadPoolExecutor编写一般的try catch块?
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////原始问题的结尾////// ////////
//////////END OF ORIGINAL QUESTION //////////////
如下所示,Decorator工作正常。
As suggested the following Decorator works well.
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
推荐答案
我写了一个小的发布关于这个问题一段时间。您有两个选择:
I wrote a small post about this problem a while ago. You have two options:
- 使用解决方案由Colin Herbert或
- 使用修改版本的Mark Peters 解决方案,而不是分配一个
UncaughtExceptionHandler
将每个提交的可运行文件包装成可运行的您自己执行(调用运行
)在try-catch块内的真正可运行的。
- Use the solution provided by Colin Herbert or
- use a modified version of Mark Peters solution but instead of assigning a
UncaughtExceptionHandler
you wrap each submitted runnable into a runnable of your own which executes (callsrun
) the real runnable inside a try-catch-block.
编辑
如Mark所指出的,将 Runnable
传递到 ScheduledExecutorService
而不是传递给 ThreadFactory
的那个。
EDIT
As pointed out by Mark, it's important to wrap the Runnable
passed to ScheduledExecutorService
instead of the one passed to the ThreadFactory
.
这篇关于ThreadPools中的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!