Java Language Handle Rejected Execution


Example

If

  1. you try to submit tasks to a shutdown Executor or
  2. the queue is saturated (only possible with bounded ones) and maximum number of Threads has been reached,

RejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor) will be called.

The default behavior is that you'll get a RejectedExecutionException thrown at the caller. But there are more predefined behaviors available:

  • ThreadPoolExecutor.AbortPolicy (default, will throw REE)
  • ThreadPoolExecutor.CallerRunsPolicy (executes task on caller's thread - blocking it)
  • ThreadPoolExecutor.DiscardPolicy (silently discard task)
  • ThreadPoolExecutor.DiscardOldestPolicy (silently discard oldest task in queue and retry execution of the new task)

You can set them using one of the ThreadPool constructors:

public ThreadPoolExecutor(int corePoolSize,
                      int maximumPoolSize,
                      long keepAliveTime,
                      TimeUnit unit,
                      BlockingQueue<Runnable> workQueue,
                      RejectedExecutionHandler handler) // <--

public ThreadPoolExecutor(int corePoolSize,
                      int maximumPoolSize,
                      long keepAliveTime,
                      TimeUnit unit,
                      BlockingQueue<Runnable> workQueue,
                      ThreadFactory threadFactory,
                      RejectedExecutionHandler handler) // <--

You can as well implement your own behavior by extending RejectedExecutionHandler interface:

void rejectedExecution(Runnable r, ThreadPoolExecutor executor)