Question

I am trying to see whether it's possible to shutdownNow() an ExecutorService which still has tasks in execution.

public static void main (String []args) throws  InterruptedException
{
    ExecutorService exSer = Executors.newFixedThreadPool(4);

    List<ExecutorThing> lista = new ArrayList<>();
lista.add(new ExecutorThing());
lista.add(new ExecutorThing());
lista.add(new ExecutorThing());
lista.add(new ExecutorThing());
lista.add(new ExecutorThing());

    List<Future<Object>> futureList = exSer.invokeAll(lista);
    exSer.shutdownNow();

and class ExecutorThing is the following:

public class ExecutorThing implements Callable<Object>{
    public Object call()  {

        while (!(Thread.currentThread().isInterrupted()))
        for (int i=0;i<1;i++)
        {
            System.out.println(Thread.currentThread().getName());
        }
            return null;
        }
}

I wonder why it never stops even though I check for the interrupt flag... and shutdownNow should terminate the tasks via interrupt().

Where am I wrong?

Thanks in advance.

PS in this question they offer as a solution the same thing I used, However it does not work to me. Maybe because I use invokeAll?

Thanks in advance.

Was it helpful?

Solution

The answer is quite simple, you just need to carefully read the Javadoc of invokeAll:

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

(emphasis mine).

In other words, your shutdownNow never gets executed. I changed your code to this:

public class Test {
  public static void main (String []args) throws  InterruptedException
  {
    ExecutorService exSer = Executors.newFixedThreadPool(4);
    exSer.submit(new ExecutorThing());
    exSer.submit(new ExecutorThing());
    exSer.submit(new ExecutorThing());
    exSer.submit(new ExecutorThing());
    exSer.shutdownNow();
  }
}

class ExecutorThing implements Callable<Object> {
  public Object call() throws InterruptedException  {
    while (!(currentThread().isInterrupted()))
      System.out.println(currentThread().isInterrupted());
    return null;
  }
}

Not surprisingly, now it behaves just as you expect it to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top