gpt4 book ai didi

java - 从 UncaughtExceptionHandler 中重新执行任务?

转载 作者:太空宇宙 更新时间:2023-11-04 08:44:29 25 4
gpt4 key购买 nike

我已经看到了一些类似的讨论,但没有看到我的问题的具体答案。当线程由于未捕获的异常而死亡时,我想重新启动任务。从垂死线程上设置的 UncaughtExceptionHandler 调用 pool.execute(runnable) 是否安全?

理想情况下,如果可抛出的异常是 RuntimeException,我只想将可运行的异常重新提交到池中,例如


pool = Executors.newFixedThreadPool(monitors.size(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
threadMap.put(thread, (Monitor)r);
thread.setName(((Monitor)r).getClusterName() + "-monitor");
thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread th, Throwable t) {
logger.error("Uncaught exception in thread: " + th.getName(), t);
if (t instanceof RuntimeException) {
Monitor m = threadMap.get(th);
if (m != null && m.runCount() < restartMax) {
logger.error("Restarting monitor due to uncaughtException: " + m.getClusterName());
pool.execute(m);
} }
}
});
return thread;
}
});

有更好的方法或更安全的方法吗?

谢谢!

最佳答案

最安全的选择是仅抛出致命的运行时异常。如果可以安全地忽略运行时异常,为什么它不被捕获并继续?

看起来你的线程映射就像一个ThreadLocal,似乎一旦一个任务使用了你所有的restartMax,它就不会再重新启动一个任务?

我这样做的方法是包装正在执行的 Runnable。

public void submit(final Runnable runnable, final int restartMax) {
pool.submit(new Runnable() {
public void run() {
for(int i=0;i<restartMax;i++)
try {
runnable.run();
break;
} catch (Exception e) {
log.error("Exception", e);
}
}
}
}

关于java - 从 UncaughtExceptionHandler 中重新执行任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4606668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com