When the thread pool queue is full and a new task is submitted, what happens depends on the thread pool’s rejection policy.
Let’s break it down clearly 👇
🧠 ThreadPoolExecutor Mechanics Recap
When you submit a task:
- If fewer threads than
corePoolSize
are running → a new thread is created. - If
corePoolSize
threads are busy → task goes to the queue. - If the queue is full and the number of threads is less than
maximumPoolSize
→ a new thread is created. - If the queue is full and the number of threads is at max → task is rejected.
🚨 What Happens When Rejected?
Java’s ThreadPoolExecutor
uses a RejectedExecutionHandler to determine what to do. There are four built-in policies:
Policy | Behavior |
---|---|
AbortPolicy (default) | Throws RejectedExecutionException |
CallerRunsPolicy | Runs the task in the caller’s thread |
DiscardPolicy | Silently drops the task |
DiscardOldestPolicy | Drops the oldest queued task, then retries submission |
💡 Example:
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10);
ThreadPoolExecutor executor = new ThreadPoolExecutor(
4, // corePoolSize
8, // maximumPoolSize
60, TimeUnit.SECONDS, // keepAliveTime
queue,
new ThreadPoolExecutor.AbortPolicy() // rejection policy
);
If:
- 8 threads are already running
- the queue has 10 tasks
- You submit task #19
→ it will throwRejectedExecutionException
.
🛠️ Want Custom Behavior?
You can also define your own policy:
executor.setRejectedExecutionHandler((r, e) -> {
System.out.println("Custom handling of rejected task: " + r);
});