ThreadPoolExecutor Block When Queue Is Full?

前端 未结 8 1825
无人及你
无人及你 2020-11-29 17:42

I am trying to execute lots of tasks using a ThreadPoolExecutor. Below is a hypothetical example:

def workQueue = new ArrayBlockingQueue(3, f         


        
8条回答
  •  温柔的废话
    2020-11-29 18:12

    A fairly straightforward option is to wrap your BlockingQueue with an implementation that calls put(..) when offer(..) is being invoked:

    public class BlockOnOfferAdapter implements BlockingQueue {
    
    (..)
    
      public boolean offer(E o) {
            try {
                delegate.put(o);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
            return true;
      }
    
    (.. implement all other methods simply by delegating ..)
    
    }
    

    This works because by default put(..) waits until there is capacity in the queue when it is full, see:

        /**
         * Inserts the specified element into this queue, waiting if necessary
         * for space to become available.
         *
         * @param e the element to add
         * @throws InterruptedException if interrupted while waiting
         * @throws ClassCastException if the class of the specified element
         *         prevents it from being added to this queue
         * @throws NullPointerException if the specified element is null
         * @throws IllegalArgumentException if some property of the specified
         *         element prevents it from being added to this queue
         */
        void put(E e) throws InterruptedException;
    

    No catching of RejectedExecutionException or complicated locking necessary.

提交回复
热议问题