Kirill
Kirill

Reputation: 1610

How can I shutdown CompletionService

I need to do something like this:

ExecutorService executor = Executors.newFixedThreadPool(2);
CompletionService<Boolean> completionService = new ExecutorCompletionService<>(executor);
int i = 0;
while (i < 40) {
  completionService.submit(getTask());
  i++;
}
executor.shutdown();
System.out.println("SHUTDOWN");

But after calling shutdown on executor object completionService still execute tasks.

How can I make it stop?

Is there are any way to stop ExecutorService but wait for the completion of currently executing tasks?

Upvotes: 1

Views: 3831

Answers (2)

Bhushan Bhangale
Bhushan Bhangale

Reputation: 10987

Use shutdownNow() which will try to stop already executing task. Read this https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#shutdownNow()

The shutdown of already executing task is an attempt only but will not be guaranteed to stop.

The shutdown() method only stops taking new tasks but already executing task will continue to execute.


UPDATE for the "Is there are any way to stop ExecutorService but waiting for completion currently executed tasks?"

One option I can think of is this -

The completionService.submit(getTask()); return object of type Future. You can write code to check if the task isDone(). After calling shutdownNow() you can check the tasks in a loop for isDone(). You need to store the tasks in list when returned by submit method.

Upvotes: 2

Boris the Spider
Boris the Spider

Reputation: 61148

The ExecutorService will carry on executing tasks already submitted but will not allow further tasks to be submitted, from the documentation

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.
emphasis mine

So you have already submitted 40 tasks, these will be executed before shutdown.

If you want to force shutdown. You can use shutdownNow:

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
emphasis mine

Which will abandon scheduled tasks, as you want.

N.B.: Stopping tasks in progress is another issue entirely.

Upvotes: 3

Related Questions