Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

BlockingQueue: inserting, removing, and inspecting elements

Choose between immediate operations, timed waits, and waits with no timeout. Learn how to inspect the queue and why its head is not always the oldest item.

Version: Java SE 21

Syntax

java.util.concurrent.BlockingQueue<E> — Java SE 21
boolean offer(E e);
boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException;
E poll();
E poll(long timeout, TimeUnit unit) throws InterruptedException;
void put(E e) throws InterruptedException;
E take() throws InterruptedException;
E peek();
int size();

The BlockingQueue.offer/poll/put/take/peek/size methods let producers and consumers work with a thread-safe queue in java.util.concurrent. offer(e) does not wait for space: it returns true if it inserts the element or false if no space is available. offer(e, timeout, unit) waits for space if necessary and returns false if the timeout expires before space becomes available. put(e) returns void and waits for space if needed, with no timeout.

poll() removes and returns the head, or returns null if the queue is empty, without waiting for an element. poll(timeout, unit) also removes and returns the head, but can wait for an element and returns null if the timeout expires first. take() removes and returns the head, waiting if needed with no timeout. Both timed overloads use a TimeUnit, as in 1, TimeUnit.MILLISECONDS. Those overloads, put, and take throw InterruptedException if the thread is interrupted while waiting.

peek(), inherited from Queue, returns the head without removing it, or null if empty. size(), inherited from Collection, returns the element count as an int, not the capacity. If the queue contains more than Integer.MAX_VALUE elements, it returns Integer.MAX_VALUE. Another thread can change the queue between calls: size() > 0 does not guarantee that a subsequent take() will not wait. Inserting null with offer or put throws NullPointerException.

ArrayBlockingQueue has a fixed capacity; LinkedBlockingQueue lets you specify a capacity limit. Both order elements FIFO: of the elements still queued, the earliest inserted is removed first. The interface itself does not guarantee FIFO. PriorityBlockingQueue removes the least element under natural ordering or a supplied comparator and does not guarantee an order among ties. It has no intrinsic capacity limit, so its put and timed offer do not wait for space.

Examples

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> fifo = new ArrayBlockingQueue<>(2);
        fifo.put(20);
        System.out.println("offer with space: " + fifo.offer(10));
        System.out.println("offer when full: " + fifo.offer(30));
        System.out.println("timed offer when full: "
                + fifo.offer(30, 1, TimeUnit.MILLISECONDS));
        System.out.println("peek: " + fifo.peek());
        System.out.println("size after peek: " + fifo.size());
        System.out.println("take: " + fifo.take());
        System.out.println("poll: " + fifo.poll());
        System.out.println("poll when empty: " + fifo.poll());
        System.out.println("timed poll when empty: "
                + fifo.poll(1, TimeUnit.MILLISECONDS));

        BlockingQueue<Integer> priority = new PriorityBlockingQueue<>();
        priority.put(20);
        priority.put(10);
        System.out.println("priority take: " + priority.take());
    }
}

Result

offer with space: true
offer when full: false
timed offer when full: false
peek: 20
size after peek: 2
take: 20
poll: 10
poll when empty: null
timed poll when empty: null
priority take: 10

Two elements fill the FIFO queue. `peek()` shows `20` but leaves the size at `2`. `take()` removes `20`, then `poll()` removes `10`. The two `1` ms calls show the failure results, not the elapsed time. The priority queue removes `10` first.

Related lessons

  • Java · Lesson 37 · Advanced · Version: 2

Sources