Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a Callable submitted to ExecutorService?

I'm trying to implement a sample application to test Callable and ExecutorService interfaces.

In my app I have declared:

ExecutorService exSvc = Executors.newSingleThreadExecutor();

Then:

Future<Integer> test = exSvc.submit(
    new Callable<Integer>() {
        public Integer call() {
            for(int i = 0; i < 1000; i++){
                System.out.println(i);
            }
            return 1;
        }
    });

Now I'm trying to stop the process before it terminate, I'm using exSvc.shutdownNow() but it doesn't work.

To stop gracefully a classical Thread I usually use some kind of condition variable. Which is a common approach to follow with ExecutorService?

like image 664
davioooh Avatar asked Jul 11 '12 09:07

davioooh


2 Answers

Future.cancel(true) and ExecutorService.shutdownNow() use thread interruption. As long as you don't make uninterruptable blocking calls in your task, all you need is to handle interrupted condition correctly, something like this:

for(int i = 0; i < 1000; i++){
    // Uses isInterrupted() to keep interrupted status set
    if (Thread.currentThread().isInterrupted()) {
        // Cannot use InterruptedException since it's checked
        throw new RuntimeException(); 
    }
    System.out.println(i);
}

If you make uninterruptable blocking calls (such as network IO), things become more complex, you need to interrupt them manually somehow, for example, by closing the underlying sockets.

like image 52
axtavt Avatar answered Sep 21 '22 12:09

axtavt


This is how I'd do it with a FixedThreadPool, hope it's of some help.

    ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    List<Future<Void>> results = new ArrayList<>();

    for (int i = 0; i < numberOfJobs; i++) {
        MyCallableJob job = new MyCallableJob (...);
        results.add(pool.submit(job));
    }

    for (Future<Void> result : results) {
        try { result.get(); }
        catch (InterruptedException | ExecutionException ignorable) { }
    }

    pool.shutdown();
like image 35
ioreskovic Avatar answered Sep 19 '22 12:09

ioreskovic