Handle Rejected Execution
suggest changeIf
- you submit a task to an executor that has been shut down, or
- a bounded queue is full and the pool is already at its maximum thread count,
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 (runs the task on the caller’s thread, which blocks that thread, unless the executor is already shut down, in which case the task is discarded)
- ThreadPoolExecutor.DiscardPolicy (silently discards the task)
- ThreadPoolExecutor.DiscardOldestPolicy (if the executor is still running, discards the next queued task and retries the new one; if it is shut down, discards 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 also supply your own behavior by implementing the RejectedExecutionHandler interface:
void rejectedExecution(Runnable r, ThreadPoolExecutor executor)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents