gpt4 book ai didi

java - 处理 Java ExecutorService 任务的异常

转载 作者:太空宇宙 更新时间:2023-11-04 09:26:56 26 4
gpt4 key购买 nike

我正在尝试使用 Java 的 ThreadPoolExecutor 类以固定数量的线程运行大量重量级任务。每个任务都有很多地方可能会因异常而失败。

我对 ThreadPoolExecutor 进行了子类化,并重写了 afterExecute 方法,该方法应该提供运行任务时遇到的任何未捕获的异常。但是,我似乎无法让它发挥作用。

例如:

public class ThreadPoolErrors extends ThreadPoolExecutor {
public ThreadPoolErrors() {
super( 1, // core threads
1, // max threads
1, // timeout
TimeUnit.MINUTES, // timeout units
new LinkedBlockingQueue<Runnable>() // work queue
);
}

protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if(t != null) {
System.out.println("Got an error: " + t);
} else {
System.out.println("Everything's fine--situation normal!");
}
}

public static void main( String [] args) {
ThreadPoolErrors threadPool = new ThreadPoolErrors();
threadPool.submit(
new Runnable() {
public void run() {
throw new RuntimeException("Ouch! Got an error.");
}
}
);
threadPool.shutdown();
}
}

该程序的输出是“一切都很好——情况正常!”即使提交到线程池的唯一 Runnable 抛出异常。对这里发生的事情有任何线索吗?

谢谢!

最佳答案

警告:需要注意的是,此解决方案将阻塞 future.get() 中的调用线程。

<小时/>

如果要处理任务抛出的异常,那么通常最好使用Callable而不是Runnable

Callable.call() 允许抛出已检查的异常,并且这些异常会传播回调用线程:

Callable task = ...
Future future = executor.submit(task);
// do something else in the meantime, and then...
try {
future.get();
} catch (ExecutionException ex) {
ex.getCause().printStackTrace();
}

如果Callable.call()抛出异常,该异常将被包装在ExecutionException中并由Future.get()抛出。

这可能比子类化 ThreadPoolExecutor 更可取。如果异常是可恢复的,它还使您有机会重新提交任务。

关于java - 处理 Java ExecutorService 任务的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57567043/

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