Search code examples
javamultithreadingexecutorservice

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.


Solution

  • 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.