tkja
tkja

Reputation: 2030

Exit from Java Callable if Exception occured

I am using ExecutorService and Callable in Java. The class implementing Callable does some IO work on the filesystem. How do I stop the execution of a callable and exit from it, if an Exception occurs?

This is an example class implementing Callable that has two methods, foo1() and foo2()

public class MyCallable<Object> implements Callable<Object> {
    public Object call() throws IOException, SQLException {
        // method 1 , could throw IOException
        foo1();
        // method 2 , could throw SQLException
        foo2();
        return null;
    }
}

This is the example execution service class. It can deal with exceptions occurred during the parallel processing through the futures object.

public class MyExecutorService {
    ExecutorService listProcessor;
    listProcessor = Executors.newFixedThreadPool(2);
    List<Callable<Object>> callableTodo = new ArrayList<Callable<Object>>();

    // add the callables to the todo list
    callableTodo.add(new MyCallable<Object>());
    callableTodo.add(new MyCallable<Object>());

    // start the threads
    List<Future<Object>> futures = listProcessor.invokeAll(callableTodo);
    listProcessor.shutdown();
    listProcessor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

    // futures now holds possible exceptions
    for (Future<Object> future : futures) {
     try {
        future.get();
     } catch (ExecutionException e) {
         // process the exception
     }
    }
}

But I would like to immediately let the MyCallable stop if for example a IOException occurs in foo1(), and not let it continue with foo2();

EDIT: Also, if an unchecked exception such as a RuntimeException occurs in foo1(), MyCallable also needs to stop.

Upvotes: 0

Views: 1545

Answers (1)

Powerlord
Powerlord

Reputation: 88786

The signature of Callable<V>'s call method is

V call() throws Exception

and its description is

Computes a result, or throws an exception if unable to do so.

In other words, just don't catch the IOException. If you don't catch it, then execution stops and the exception is passed up a level.

Note: this only works for non-RuntimeExceptions if the method is marked as throwing an exception type, which call is marked as doing because it's declared as throws Exception.

As you're already aware, Future's .get method will throw an ExecutionException if the Callable throws an exception.

Upvotes: 2

Related Questions