Java.Multithreading.What happens if the thread pool queue is already full but a new task is submitted?

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:

  1. If fewer threads than corePoolSize are running → a new thread is created.
  2. If corePoolSize threads are busy → task goes to the queue.
  3. If the queue is full and the number of threads is less than maximumPoolSize → a new thread is created.
  4. 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:

PolicyBehavior
AbortPolicy (default)Throws RejectedExecutionException
CallerRunsPolicyRuns the task in the caller’s thread
DiscardPolicySilently drops the task
DiscardOldestPolicyDrops 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 throw RejectedExecutionException.

🛠️ Want Custom Behavior?

You can also define your own policy:

executor.setRejectedExecutionHandler((r, e) -> {
    System.out.println("Custom handling of rejected task: " + r);
});
This entry was posted in Без рубрики. Bookmark the permalink.