简体   繁体   中英

Understanding java executor service shutdown and awaitTermination

need to clarify following behaviour.

I have a java app with java.util.concurrent.ExecutorService as follows,

       for (int i = 0; i < thread_count; i++) {
            Runnable worker = new MyThread(batchSize);
            executor.execute(worker);
        }

        executor.shutdown();
        executor.awaitTermination(15, TimeUnit.MINUTES);
        System.out.println("All threads are finished");

In above code I have 5 threads and those are finished in 10 minutes and it will execute System.out.println("All threads are finished") , even-though executor.awaitTermination(15, TimeUnit.MINUTES) has 15 minutes wait time.

But when I remove executor.shutdown() the program will wait 15 minutes which is specified in executor.awaitTermination(15, TimeUnit.MINUTES) statement, before executing next line.

Can any one explain this behaviour ? Why without shutdown command will wait specified amount of time evengthough all the threads are finished ?

The Javadoc for ExecutorService.awaitTermination says:

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs , or the current thread is interrupted, whichever happens first .

So when you call shutdown(): your threads are finished in 10 minutes. Then awaitTermination returns immediately (without waiting for 15 minutes to pass).

But if you remove the call to shutdown(), there's no shutdown request, so awaitTermination does not return until the timeout passes (15 minutes)

The Javadoc for ExecutorService.awaitTermination method states:

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

The ExecutorService will immedietly start all tasks that are handed over to him.

ExecutorService#shutdown will cause the ExecutorService to stop accepting new tasks and finish the work (start all previous supplied tasks that aren't started till now).

The arguments for ExecutorService#awaitTermination are the timeout, the amount of time this call will block before it forcefully returns.

In your scenario without calling shutdown() your call to awaitTermination() will block for the full amount of supplied time, because the Executor itself will wait for new work for ever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM