Shutdown or Not Shutdown? in ExecutorService (Java8)

梦想的初衷 提交于 2019-12-14 01:46:53

问题


I am trying to understand the behaviour of the executor service relative to shutdown. The documentation says that the application won't terminate unless there is a shutdown() call - but in this simple example. It exits after one minute precisely. Any idea?

 Runnable r = new Runnable() {
            @Override
            public void run() {
                Print.println("do nothing");
            }
        };
        ThreadFactory TF = (Runnable run) -> new Thread(run);
        ExecutorService exec = Executors.newCachedThreadPool(TF);
        exec.submit(r);

returns this: 11:34:00.421 : Thread-0: do nothing BUILD SUCCESSFUL (total time: 1 minute 0 seconds)


回答1:


You are using CachedThreadPool. It keeps the thread alive for 60 secs so that next subsequent tasks do not waste time in creating new thread resource. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html

The internal code -

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

You should call shutdown() once the job is done.



来源:https://stackoverflow.com/questions/29098117/shutdown-or-not-shutdown-in-executorservice-java8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!