ForkJoinPool::shutdown vs ForkJoinPool::shutdownNow after ForkJoinPool::join

Viewed 109

Code:

            final ForkJoinPool forkJoinPool = new ForkJoinPool(PARALLELISM_NUMBER);
            try {
                final List<Record> records = getRecrods();
                List<List<Record>> partitionRecordLists = Lists.partition(records, BATCH_SIZE);

                forkJoinPool.submit(() ->
                        partitionRecordLists.parallelStream().forEach(this::performSomething)
                ).join();
                
            } finally {
                forkJoinPool.shutdown();
            }

I have above code to perform some tasks in parallel. Given that join already makes caller thread wait until completion, wondering if it should be shutdowNow() instead of shutdown() in the finally block.

Note:performSomething only reads from the input list.

1 Answers

Generally: shutdown(); implies you are doing clean / ordered shutdown for the executor service, and shutdownNow(); used for particular circumstances - often for error handling or to bypass any not started and less-important background services.

In you case there would not be any difference as you use join(). However consider another person maintaining your code: the join() is less obvious to see inside the code block so they would find it strange to see forkJoinPool.shutdownNow(); at the end without a comment explaining why that was OK there, and shutdown() is more obvious neater way to indicate that the end of pool processing has completed.

final ForkJoinPool forkJoinPool = new ForkJoinPool(...);
try {
    // Long block:
    // harder to spot join() here whereas shutdown() stands out
} finally {
    forkJoinPool.shutdown();
}
Related