Darshan Dagly
Darshan Dagly

Reputation: 1

ExecutorService awaitTermination does not wait for threads to complete and terminates main thread immediately

I have created a ExecutorService having 3 threads using which I'm trying to process a list each having 2MM objects. I'm calling below 2 methods after submitting the 3 tasks.

executorService.shutdown();
executorService.awaitTermination(20, TimeUnit.HOURS);

However, once the 3 threads start execution, the main thread terminates without waiting for the processing threads to complete execution. What am I missing?

ExecutorService executorService = new ThreadPoolExecutor(3, 3, 1L, TimeUnit.MINUTES, 
new LinkedBlockingQueue<>(BLOCKING_QUEUE_SIZE), new ThreadPoolExecutor.CallerRunsPolicy());

List<List<String>> listOfList = new ArrayList<>(); // Each list in this list has 2MM.
for (List<String> list : listOfList) {
    executorService.submit(() -> processList(list));
}

executorService.shutdown();            
final boolean awaitTermination = executorService.awaitTermination(20, TimeUnit.HOURS);
if (awaitTermination) {
    System.out.print("Await Termination returned True\n");
} else {
    System.out.print("Await Termination returned False\n");
}

System.out.printf("Terminating main thread!\n");

The processList method looks something like -

private void processList(List<String> list) {

final String uuid = UUID.randomUUID().toString();
System.out.printf("UUID - %s\n", uuid);

// Process the list. This takes about 1hr

System.out.printf("UUID - %s - Completed processing!\n", uuid);
}

Output -

UUID - 448553ca-93ba-459e-a864-a3f1bf2aadf1
UUID - da43f632-ff75-42d2-9244-bc3c1fb834ea
UUID - 9f028167-eef0-4017-903e-9246d8670dee
Await Termination returned True
Terminating main thread!

Upvotes: 0

Views: 72

Answers (0)

Related Questions