gpt4 book ai didi

java - 异常处理 ScheduledExecutorService

转载 作者:行者123 更新时间:2023-11-30 05:31:58 25 4
gpt4 key购买 nike

我使用 ScheduledExecutorService1 分钟 的固定间隔运行线程。

ScheduledExecutorService 的一个实例运行一个线程,另一个实例运行另一个线程。

示例:

ses1.scheduleAtFixRate(..) // for thread 1  
ses2.scheduleAtFixRate(..) // for thread 2

我遇到了一些异常,导致进一步的执行停止。我想捕获应用程序系统关闭的异常。

我应该使用第三个线程来处理异常,该线程监视 future 并处理异常,还是有其他更好的方法?会不会影响其他线程。

感谢任何及所有帮助!

最佳答案

I was encountering some exceptions by which the further execution stops.

根据规范,这是 ScheduledExecutorService.scheduleAtFixRate() 的预期行为:

If any execution of the task encounters an exception, subsequent executions are suppressed.

关于您的需求:

I want to catch the exception for a systematic shutdown of my application.
Should I handle the exception using a third thread that monitors both futures and handles the Exception or is there any other better way?

使用 ScheduledFuture.get() 处理 future 的返回看起来是正确的。根据 ScheduledFuture.scheduleAtFixedRate() 规范:

Otherwise, the task will only terminate via cancellation or termination of the executor.

因此您甚至不需要创建新的预定 future 。
只需运行两个并行任务(也可以使用 ExecutorService 或两个线程),等待每个 Futureget() 并停止应用程序如果任务中抛出异常:

Future<?> futureA = ses1.scheduleAtFixRate(..) // for thread 1  
Future<?> futureB = ses2.scheduleAtFixRate(..) // for thread 2
submitAndStopTheApplicationIfFail(futureA);
submitAndStopTheApplicationIfFail(futureB);

public void submitAndStopTheApplicationIfFail(Future<?> future){
executor.submit(() -> {
try {
future.get();
} catch (InterruptedException e) {
// stop the application
} catch (ExecutionException e) {
// stop the application
}
});
}

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

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