我需要在一个方法中正确关闭两个 Executor Service 实例。
这是我简化后的代码:
ExecutorService executor1 = Executors.newSingleThreadExecutor();
ScheduledExecutorService executor2 = Executors.newSingleThreadScheduledExecutor();
// logic here
executor1.shutdown();
executor2.shutdown();
try {
if (!executor1.awaitTermination(1, TimeUnit.SECONDS)) {
executor1.shutdownNow();
}
} catch (InterruptedException ex) {
throw new IllegalStateException(ex);
}
try {
if (!executor2.awaitTermination(1, TimeUnit.SECONDS)) {
executor2.shutdownNow();
}
} catch (InterruptedException ex) {
throw new IllegalStateException(ex);
}
InterruptedException
被转换为IllegalStateException
,因为我不希望在这里发生任何中断,如果发生中断会导致我的应用程序进入非法状态。
我认为这个解决方案存在一个缺陷 - 每当第一个执行器在关闭时抛出异常时,第二个执行器将无法正确关闭。在这里应该采取什么正确的方法?如何安全地关闭两个ExecutorService
实例?
我宁愿避免嵌套的try-finally
块,因为我可能需要添加第三个执行器服务,代码会变得难以管理。