How to Create a Blocking ExecutorService in Java When the Queue Size is Reached?

Question

How can I configure a Java ExecutorService to block submissions when the task queue size reaches a limit?

ThreadPoolExecutor executor = new ThreadPoolExecutor(numWorkerThreads, numWorkerThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>(maxQueue));

Answer

In Java, the ThreadPoolExecutor can be customized to handle task submissions when the queue is full without throwing rejected execution exceptions. Instead of allowing tasks to be rejected, we can implement a blocking mechanism for the submit operation to wait until capacity is available in the queue.

BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(maxQueue); // Blocking behavior on overflow
ThreadPoolExecutor executor = new ThreadPoolExecutor(numWorkerThreads, numWorkerThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  blockingQueue) {
    @Override
    public void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        try {
            if (blockingQueue.remainingCapacity() == 0) {
                // Block until there's space in the queue
                synchronized (this) {
                    while (blockingQueue.remainingCapacity() == 0) {
                        wait();
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
};

Causes

  • The `ExecutorService` is configured with a limited-sized queue.
  • All worker threads are busy processing tasks, filling up the queue.
  • Subsequent submissions may lead to the `RejectedExecutionException` if the queue reaches its limit.

Solutions

  • Use a custom BlockingQueue that supports waiting on enqueue operations.
  • Implement a wrapper around the `ExecutorService` to block the current thread until there is space in the queue.
  • Consider using methods like `executor.awaitTermination()` after submitting tasks to manage the queue effectively.

Common Mistakes

Mistake: Using the default `CallerRunsPolicy`, which reverts execution to the calling thread, blocking further submissions.

Solution: Instead, implement a custom blocking strategy or use a dedicated blocking queue.

Mistake: Not handling `InterruptedException` when waiting on the queue.

Solution: Always check and handle thread interruption properly to ensure stability.

Helpers

  • Java ExecutorService
  • Blocking ExecutorService
  • ExecutorService Task Submission
  • ThreadPoolExecutor
  • Java Concurrency

Related Questions

⦿How to Encrypt a String Using AES with a Custom Key in Java?

Learn how to use AES encryption in Java with your custom key including key length issues and cipher modes.

⦿How to Read a UTF-8 File without the BOM Marker in Java

Learn how to read a UTF8 encoded file in Java while removing the BOM marker from the output.

⦿How to Make Asynchronous HTTP Requests in Java

Learn how to implement asynchronous HTTP requests in Java allowing nonblocking execution with callbacks for improved performance.

⦿How to Calculate the Difference in Seconds Between Two Dates in Java

Learn how to calculate the difference in seconds between two dates in Java using java.time API and avoid common mistakes.

⦿Resolving the 'Access Restriction' Error When Using JavaFX in JRE 8

Learn how to fix the Access restriction error in Eclipse when working with JavaFX in Java 8 projects. Detailed solutions and tips provided.

⦿How to Decode a SHA-256 Hashed and Base64 Encoded String?

Learn how to decode a SHA256 hashed and base64 encoded string and understand key concepts surrounding hashing for better security practices.

⦿What is a Keystore and How Does it Relate to SSL?

Learn what a keystore is and its role in SSL communication. Understand the exception errors related to SSL and how to resolve them effectively.

⦿How to Manipulate the Alpha Component of a Color Int in Java for Android?

Learn how to adjust the alpha bytes of an Android color int in Java. Stepbystep guide with code snippets for transparency manipulation.

⦿How to Implement a Sorted Array List in Java While Preserving Duplicates

Discover how to create a sorted list in Java that maintains duplicates with expert insights and code examples.

⦿How to Retrieve Raw XML from SOAPMessage in Java

Learn how to extract raw XML from a SOAPMessage in Java JAXWS with a stepbystep guide and code examples.

© Copyright 2025 - CodingTechRoom.com