【问题标题】:Monitoring runtime exceptions thrown by ThreadPoolExecutor监控 ThreadPoolExecutor 抛出的运行时异常
【发布时间】:2019-05-08 07:16:52
【问题描述】:

我正在使用 ThreadPoolExecutor,有几个消息提供线程将消息输入其中以进行处理。每个线程在提交之前都会检查执行器的深度。如果深度超过某个阈值,那么线程将等待一定的时间并再次检查。只有当它发现深度低于阈值时才会提交。所以我认为执行者不会因为太多消息而爆炸。但是,我仍然想知道我需要注意哪些例外情况。我只从 api "RejectedExecutionException" 中找到了可以来自执行程序的:

当 Executor 已关闭,以及 Executor 对最大线程和工作队列容量都使用有限边界且已饱和时,在方法 execute(java.lang.Runnable) 中提交的新任务将被拒绝。

RejectedExecutionException 是我需要在日志中注意的唯一异常吗?有人遇到执行人陷入困境的情况吗?在那种情况下会发生什么?我们还会看到 RejectedExecutionException 吗?还有其他可能的例外吗?非常感谢!

【问题讨论】:

    标签: runtimeexception threadpoolexecutor


    【解决方案1】:

    我根据经验发现,与使用 Executors 相比,您需要有一个辅助函数来提供根 Exception 类,以便您可以正确记录它以进行诊断。 发生这种情况是因为一些执行程序抛出 java.util.concurrent.TimeoutException,其他人抛出 java.util.concurrent.ExecutionException 取决于实现所以我想出了下面的接口

    UnaryOperator<Throwable> flatEx = t -> 
        t.getCause() == null ? t : 
            t.getCause().getCause() == null ? t.getCause() :
                t.getCause().getCause().getCause() == null ? t.getCause().getCause() : 
                    t.getCause().getCause().getCause();
    

    【讨论】:

    • 谢谢@Gabriel Hernandez。所以你会在 catch 块中使用一元运算符来捕获从提交到执行程序的任何内容?像这样:try { executorService.execute(task); } catch (Throwable e) { LOGGER_ERROR.error(flatEx.apply(e)); }
    • 是的,这是获取异常根本原因的好方法,通过这种方式,您可以根据异常类或异常消息返回正确的错误代码或触发事件
    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 2015-06-03
    • 2013-10-28
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    相关资源
    最近更新 更多