Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 626
Viraj Avatar asked Feb 22 '26 14:02

Viraj


1 Answers

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)

like image 156
Yinsi Rio Avatar answered Feb 24 '26 05:02

Yinsi Rio