Thread-safety of BlockingQueue's drainTo() method

后端 未结 3 829
说谎
说谎 2021-01-01 15:50

Documentation of BlockingQueue says bulk operations are not thread-safe, though it doesn\'t explicitly mention the method drainTo().

BlockingQueue imp

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 16:22

    stumbled upon this question and felt like adding an implementation info.

    From Java 8 source of PriorityBlockingQueue :

     /**
         * @throws UnsupportedOperationException {@inheritDoc}
         * @throws ClassCastException            {@inheritDoc}
         * @throws NullPointerException          {@inheritDoc}
         * @throws IllegalArgumentException      {@inheritDoc}
         */
        public int drainTo(Collection c, int maxElements) {
            if (c == null)
                throw new NullPointerException();
            if (c == this)
                throw new IllegalArgumentException();
            if (maxElements <= 0)
                return 0;
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                int n = Math.min(size, maxElements);
                for (int i = 0; i < n; i++) {
                    c.add((E) queue[0]); // In this order, in case add() throws.
                    dequeue();
                }
                return n;
            } finally {
                lock.unlock();
            }
        }
    

    You can see that a ReentrantLock is used to lock the critical section. The methods poll() and offer() are also using the same lock. So the BlockingQueue implementation in this case of PriorityBlockingQueue is indeed Blocking!

提交回复
热议问题