Program does not terminate immediately when all ExecutorService tasks are done

后端 未结 6 1115
一整个雨季
一整个雨季 2020-12-29 21:22

I put a bunch of runnable objects into an ExecutorService:

// simplified content of main method
ExecutorService threadPool = Executors.newCachedThreadPool();         


        
6条回答
  •  星月不相逢
    2020-12-29 21:45

    Executors.newCachedThreadPool() uses Executors.defaultThreadFactory() for its ThreadFactory. defaultThreadFactory's javadocs say that "each new thread is created as a non-daemon thread" (emphasis added). So, the threads created for the newCachedThreadPool are non-daemon. That means that they'll prevent the JVM from exiting naturally (by "naturally" I mean that you can still call System.exit(1) or kill the program to cause the JVM to halt).

    The reason the app finishes at all is that each thread created within the newCachedThreadPool times out and closes itself after some time of inactivity. When the last one of them closes itself, if your application doesn't have any non-daemon threads left, it'll quit.

    You can (and should) close the ExecutorService down manually via shutdown or shutdownNow.

    See also the JavaDoc for Thread, which talks about daemon-ness.

提交回复
热议问题