【问题标题】:Is it necessary to shutdown an ExecutorService for a webapplication running in a Tomcat container?是否需要为在 Tomcat 容器中运行的 Web 应用程序关闭 ExecutorService?
【发布时间】:2015-07-29 19:56:00
【问题描述】:

如果ExecutorService 在某个Servlet 的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();

}

【问题讨论】:

  • @Marvin 我已阅读链接中的 cmets,谢谢。但是我应该在哪里调用关闭,因为它会为连续请求引发异常。如果我不关机会发生什么?

标签: java tomcat executorservice


【解决方案1】:

ExecutorService 背后的想法是重用线程。创建线程的成本很高,通常创建一次线程然后多次使用同一个线程会更有效。这正是ExecutorService 所做的事情:它管理一个(可能是空闲的)线程池,并在您调用它的submit 方法时为它们分配工作。

因此,在典型应用程序中,您不想关闭ExecutorService。但是,如果您的应用程序终止,您应该正确关闭ExecutorService。由于您使用的是 Spring,因此您不必担心:

默认情况下,使用 Java 配置定义的具有公共关闭或关闭方法的 bean 会自动加入销毁回调。 [见documentation。]

也就是说,如果你关闭ApplicationContext,Spring 会自动为你关闭ExecutorService。

【讨论】:

  • 非常感谢您的解释。 Spring 管理关闭的事实是我一直在寻找的缺失部分。
猜你喜欢
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 2019-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
  • 1970-01-01
相关资源
最近更新 更多