如果 ExecutorService
在 Tomcat 容器中运行,是否有必要在某个时刻关闭它?如果是,那么我应该在哪里调用关机?我尝试在 submit() 调用之后添加它,但是当我从客户端浏览器向 Servlet 发出另一个请求时,我得到一个 RejectedExecutionException
这可能是因为我关闭了?我试图了解它在 Tomcat 中的 Servlet 中如何工作以及我应该如何使用它。
我正在我的 webApplication 中执行以下操作(它似乎在没有任何关闭的情况下工作正常):
// In configuration class
@Bean (name = "executorService")
public ExecutorService executorService() {
return Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
}
// In some other class
@Qualifier("executorService")
@Autowired
private ExecutorService executorService;
....
private void load() {
executorService.submit(new Runnable() {
@Override
public void run() {
doSomethingInTheBackground();
}
});
// If I enable this I will get a RejectedExecutionException
// for a next request.
// executorService.shutdown();
最佳答案
ExecutorService
背后的想法是重用线程。创建线程是昂贵的,通常创建一次线程然后多次使用同一个线程会更有效。这正是 ExecutorService
所做的:它管理一个线程池(可能是空闲的)并在您调用它的 submit
方法时为它们分配工作。
因此,在典型的应用程序中,您不希望关闭 ExecutorService
。但是,如果您的应用程序终止,您应该正确关闭 ExecutorService
。由于您使用的是 Spring,因此您不必担心:
By default, beans defined using Java config that have a public close or shutdown method are automatically enlisted with a destruction callback. [See the documentation.]
这意味着,如果您关闭 ApplicationContext
,Spring 将自动为您关闭 ExecutorService
。
关于java - 在 Tomcat 容器中运行的 Web 应用程序是否需要关闭 ExecutorService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31709932/