java - Executors.newFixedThreadPool 挂起的线程

标签 java multithreading tomcat

正如它在 javadoc 中所说的那样

The threads in the pool will exist until it is explicitly shutdowned by ExecutorService#shutdown()

如果我在 Tomcat 上有一个 Web 应用程序。在启动时它创建一个固定的线程池。我也调查过

      public  static void main(String ... strings)  {
            ExecutorService s = Executors.newFixedThreadPool(2);
            s.submit(new Runnable() {
                public void run() {
                        System.out.println("zzz");
                }
            });
      }

在我将它们提交给 ExecutorService 之前,上面示例中的线程不存在。当 main 方法结束时,我在任务管理器(win 7 操作系统)的进​​程列表中看到一个 javaw.exe。所以我假设运行该示例的 jvm 实例仍然存在。当我添加 s.shutdown() - 进程列表中没有任何 java 进程。

问题一:当tomcat因为某些错误突然停止时,java进程会不会在内存中挂起(如果之前有任务提交到上述线程池);

问题 2:如果上一个问题的答案是肯定的,是否有一些方法可以使池中的线程成为守护进程,或者是否有一些方法可以处理此类 tomcat/myapp 停止调用 ExecutorService#shutdown()

最佳答案

Question 1: when the tomcat suddenly stops due to some errors, will the java process hang in the memory(if previously some tasks were submitted to thread pool mentioned above);

如果它没有关闭 ExecutorService 那么是的,它将挂起。

Question 2: if the answer to previouse question is yes, are there some ways to make threads in pool to be deamon...

是的。您可以提供一个线程工厂。

ExecutorService threadPool = newFixedThreadPool(numThreads,
    new ThreadFactory() {
        public Thread newThread(Runnable runnable) {
            Thread thread = Executors.defaultThreadFactory().newThread(runnable);
            thread.setDaemon(true);
            return thread;
        }
    });

正如@matt b 提到的,另一种确保线程池关闭的机制是 define a shutdown hook/listener in Tomcat .

关于java - Executors.newFixedThreadPool 挂起的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12425620/

相关文章:

java - 在 Android 中拦截来自 subview 的点击

javafx canvas 几秒钟后停止显示(我正在尝试百万个椭圆)

java - 在服务器 : "NB: JAVA_HOME should point to a JDK not JRE". 上设置 Tomcat 7 .. 为什么?

java - 如何知道 BLE 设备何时订阅了 Android 上的特征?

java - Jenkins 中算法协商失败

c++ - 多线程 - const char 数组作为参数传递

apache - Apache 的 META-INF/resources/extraction

java - Tomcat 无法从过多的流量中恢复

java - 准备好的语句 - 使用函数作为 where 子句的一部分

C++ 多线程服务器帮助