Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executors.newFixedThreadPool hanged threads

As it said in javadoc

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

If I have a web application on Tomcat. On startup It creates a fixed thread pool. Also I have investigated

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

that threads in the above example don't exist until I submit them to ExecutorService. When main method ends I see a javaw.exe in the list of processes of the task manger(win 7 os). So I assume that instance of the jvm that run that example still exists. When I add s.shutdown() - there are no any java process in the process list.

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);

Question 2: if the answer to previouse question is yes, are there some ways to make threads in pool to be deamon or maybe are there some ways to handle such tomcat/myapp stops to invoke ExecutorService#shutdown()

like image 804
maks Avatar asked Dec 21 '22 16:12

maks


1 Answers

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);

If it doesn't shutdown the ExecutorService then yes, it will hang.

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

Yes there is. You can provide a thread factory.

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

As @matt b mentioned, another mechanism to ensure that the thread-pool is shutdown is to define a shutdown hook/listener in Tomcat.

like image 176
Gray Avatar answered Dec 24 '22 02:12

Gray