如果执行程序服务的可调用项之一遇到错误,如何在控制台中记录错误

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

我有一个使用 executorService 的程序,我要将其传递给 callables

其中每一个都是一个 class 的对象,它实现了 java.util.concurrent.Callable.

然后 executorService 被调用。 java.lang.NoClassDefFoundError 被抛出在 call() 方法中的一个可调用对象的中间。

但是它既没有终止也没有登录到控制台。因此无法知道程序是否正确运行。请提出任何我能理解的方式。

一个Callable throws an Exception, which is not the superclass of NoClassDefFoundError。在你的 Callable 中,捕获错误(甚至是 Throwable)并用异常包装它:

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

为了将错误打印到控制台,您可以创建一个 Thread.UncaughtExceptionHander. Passing it into the Thread#setDefaultUncaughtThreadExceptionHandler 将导致在抛出错误时调用处理程序。

有人已经post回答了这个问题,但当我核实后标记为答案时,不幸的是post被删除了。我只是重新输入答案。

ExecutorService调用invoke方法后返回的Futures包含线程的所有Future对象。如果任何线程中出现任何问题,则会抛出 java.util.concurrent.ExecutionException。当我们对 Future 执行 get() 时,可以在拥有 executorService 的父线程中检测到。然后 e.getCause() 在捕获之后会得到导致 error/exception.

的实际对象