EKK
EKK

Reputation: 171

Shutdown or Not Shutdown? in ExecutorService (Java8)

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)

Upvotes: 3

Views: 2469

Answers (1)

hemant1900
hemant1900

Reputation: 1226

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.

Upvotes: 3

Related Questions