Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shutdown and awaitTermination which first call have any difference?

What is the difference between

ExecutorService eService = Executors.newFixedThreadPool(2); eService.execute(new TestThread6()); eService.execute(new TestThread6()); eService.execute(new TestThread6()); eService.awaitTermination(1, TimeUnit.NANOSECONDS); eService.shutdown(); 

and

eService.shutdown(); eService.awaitTermination(1, TimeUnit.NANOSECONDS); 

I don't really understand shutdown(). This method does not wait for previously submitted tasks to complete execution. Does it mean shutdown() may terminate the tasks which have been submitted, but not completed? I tried some examples, they do not prove it, please give me an example.

like image 817
王奕然 Avatar asked Aug 25 '13 02:08

王奕然


People also ask

What is the difference between shutdown and shutdownNow?

shutdown() will just tell the executor service that it can't accept new tasks, but the already submitted tasks continue to run. shutdownNow() will do the same AND will try to cancel the already submitted tasks by interrupting the relevant threads.

What does awaitTermination do?

The awaitTermination method of ExecutorService in Java is used to wait for all the tasks submitted to the service to complete execution: After the shutdown of the service was initiated. The wait time for the termination of the service is over. The current thread of execution is interrupted.

What is ExecutorService Java?

ExecutorService is a JDK API that simplifies running tasks in asynchronous mode. Generally speaking, ExecutorService automatically provides a pool of threads and an API for assigning tasks to it.


1 Answers

You should call shutdown first. Otherwise, you might be waiting for a very long time, since awaitTermination doesn't actually shut down your executor.

If you wanted to wait for tasks to complete, rather than wait for the executor to shut down, then you should use invokeAll.

like image 160
Chris Jester-Young Avatar answered Oct 12 '22 06:10

Chris Jester-Young