How to log an error in the console if one of the callables of the executor service encounter an error

1.5k views Asked by At

I have a program which uses executorService to which I am passing callables.

Each of which is an object of one class which implements java.util.concurrent.Callable.

Then the executorService is invoked. A java.lang.NoClassDefFoundError is thrown in the middle of one of the callables in the call() method.

However it is not terminating nor getting logged on the console. Therefore there is no way to know if the program has worked correctly or not. Kindly suggest any way by which I can understand the same.

3

There are 3 answers

0
KaustubhSV On BEST ANSWER

Some one had already posted answer to this question, but when I came to mark it as answer after verifying, the post was unfortunately deleted. I am just retyping the answer.

The Futures which are returned by the ExecutorService after calling the invoke method contain all the Future objects of the thread. If anything goes wrong in any of the threads, an java.util.concurrent.ExecutionException is thrown. Which can be detected in the parent thread which owns the executorService when we do get() on the Future. Then e.getCause() after catching it will get us the actual object which caused an error/exception.

0
Nathan Hughes On

In order to print the error to the console, you can create a Thread.UncaughtExceptionHander. Passing it into the Thread#setDefaultUncaughtThreadExceptionHandler will cause the handler to be invoked when the error is thrown.

1
Kimmy W. On

A Callable throws an Exception, which is not the superclass of NoClassDefFoundError. Within your Callable, catch Error (or even Throwable) and wrap it with an Exception:

V call() throws Exception
{
    try
    {
       return this.doSomething();
    } catch (Error e) {
      e.printStackTrace();
      throw new Exception(e);
    }
}