'How to shutdown an ExecutorService from one of its threads?

I want to stop the whole ExecutorService if one (specific thread) of the threads managed by it fails with an exception. Is it ok to simply call ExecutorService#shutdown from within the thread?



Solution 1:[1]

With Executorservice , if getting returned data from a thread ( using .get() method ) fails with an Exception , an ExecutionException will be thrown . You have 2 case : passing Runnable to the submit method , or passing a Callable , in both of those cases you can use .get() method to retrieve data from the thread after execution.

So you can add .get() method to all the execution of threads and surround the calls of the submit method with a try catch block that handle ExecutionException .

This example will explain the idea :

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
    static ExecutorService service = Executors.newFixedThreadPool(3);

    public static void main(String[] args) {

        try {

            // Callable
            System.out.println(service.submit(() -> {
                return "Hello";
            }).get());

        } catch (ExecutionException e) {
            System.out.println(e.getMessage());
            // shutDown the service : if you delete the next line , service will still
            // working
            service.shutdownNow();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            // Runnable
            service.submit(() -> {
                throw new IOException();
            }).get();

        } catch (ExecutionException e) {
            System.out.println(e.getMessage());
            // shutDown the service : if you delete the next line , service will still
            // working
            service.shutdownNow();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oussama ZAGHDOUD