Search code examples
runtimeexceptionthreadpoolexecutor

Monitoring runtime exceptions thrown by ThreadPoolExecutor


I am using a ThreadPoolExecutor, with a couple of message providing threads feeding messages into it to be processed. Each thread checks the depth of the executor before submitting. If the depth is above a certain threshold, then the thread will wait a certain amount of time and check again. It will only submit when it finds the depth below the threshold. So I don't think the executor will explode from too many messages. However, I still would like to know what exceptions I need to look out for. I have only found from api "RejectedExecutionException" that can come from the executor:

New tasks submitted in method execute(java.lang.Runnable) will be rejected when the Executor has been shut down, and also when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated.

Is RejectedExecutionException the only exception I need to look out for in the logs? Has someone run into a situation where an executor gets into a limbo state? What happens in that situation? Will we still see RejectedExecutionException? Are there any other exceptions possible? Thanks so much!


Solution

  • I found by experience than when working with Executors, you need to have an auxiliary function that provides the root Exception class so you can log it correctly for diagnostics. This happens because some executors throw java.util.concurrent.TimeoutException, others throw java.util.concurrent.ExecutionException depending on implementation so I came up with below interface

    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();