在我的配置类中,我有一个用于固定线程池的 bean
@Bean
public ExecutorService fixedThreadPool() {
return Executors.newFixedThreadPool(200);
}
我稍后会在某堂课上 Autowiring 它。在我研究的过程中,我发现这是关闭执行程序服务的最佳方法,如 java docs 所示。
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
但我还发现spring does that for you ,如果您的 ExecutorService 是一个 bean。我的问题是——这是真的吗?如果是的话,那肯定会更容易,因为我不确定将上面提到的代码放在哪里。如果我把它放在我使用这个bean的类中,我将来可能会在其他一些类中使用这个bean,这似乎是错误的。
最佳答案
是的,Spring 会为您做到这一点,但只有在容器关闭时它才会销毁 bean,您可能希望在处理完所有任务后关闭执行服务。您可以创建 ExecutorService bean 作为原型(prototype),但由于 spring 不会完全管理其生命周期,您必须在任务完成后自己调用其 destroy 方法。
关于java - spring 是否负责关闭您的 ExecutorService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50940536/