[concurrency-interest] backport: execution service shutdownNow question

Doug Lea dl at cs.oswego.edu
Tue Mar 7 07:40:31 EST 2006


Tom Sugden wrote:
> 
> I have used an execution service to invoke a collection of Callable objects
> which block indefinitely. I then call shutdownNow() on the service from
> another thread. Here is some simplified code:
> 
>     // from one thread:
>     ExecutorService service = Executors.newCachedThreadPool();
>     Collection activityProcessors = new ArrayList();
>     activityProcessors.add(new ActivityProcessor("activity1"));
>     activityProcessors.add(new ActivityProcessor("activity2"));
>     List futureResults = service.invokeAll(activityProcessors);
> 
>     // later, from another thread:
>     service.shutdownNow();
> 
> Afterwards I check the cancelled status on the Future objects associated
> with each of the Callable objects. I would have expected isCancelled() to
> return true but instead it returns false. Is this to be expected even though
> the Callable objects have been stopped at an intermediate stage due to the
> shutdownNow() call? 
> 

The shutdownNow method doesn't cancel non-run tasks because it doesn't
know what you'd like to do with them. Instead, it hands them all back to you,
so you can cancel them, run them in another executor, or whatever.

So in your case, you might write something like

    for (Runnable t : service.shutdownNow())
        if (t instanceof Future) ((Future)t).cancel(true);


-Doug


More information about the Concurrency-interest mailing list