hsluo
hsluo

Reputation: 1702

Java ExecutorService when to call shutdown()

I'm new to Java multithreading. I'm using ExecutorService to download a bunch of web pages to analyze. Currently my approach is to submit all Callables and put the Future objects in a list in a loop, then call shutdown() and awaitTermination(), finally I process the future list.
My question is in my case, is it OK to put shutdown() after filling up the future list like this? As get() of Future already blocks until the task is done, seems that I should instead call it when I finish processing all the futures.

Upvotes: 4

Views: 4458

Answers (3)

artbristol
artbristol

Reputation: 32397

There is no point using a thread pool if you shut it down after you've used it. It's designed to allow you to reuse the threads.

Instead, put the the Executor in a static field (or better, inject it with a DI framework like Spring). Then use java.util.concurrent.ExecutorService.invokeAll(Collection<? extends Callable<T>>), which blocks until all the tasks you submitted have completed.

Upvotes: 0

ajay_t
ajay_t

Reputation: 2385

There are two methods

1. shutdown()

as @Sotirios said, thread will completes the current tasks but did not add any new task for execution. So the current tasks will run to finish

2. shutdownNow()

It suddenly terminates all the tasks.

So by using the shutdown() method you can check weather all tasks are finished or not and can wait until all tasks are finished. To acheive what you want, you can use isTerminated() method in the infinite loop as

while(!isTerminated());

So when all the finished next sequential action will be taken.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

Note the javadoc of shutdown()

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.

This is a clean stop. The submitted tasks will run until they are done. Since you also have awaitTermination() which

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Your Future#get() method calls will return immediately (if the awaitTermination() didn't time out). There is no issue with what you are doing.


Make sure your tasks don't run forever.

Upvotes: 1

Related Questions