NOTE

6.27 BlockingQueue

1. What it is. A thread-safe blocking queue. Characteristics: FIFO; blocking insertion when the queue is full and blocking removal when the queue is empty; bounded or unbounded capacity; thread safety. 2. Use cases. Producer-consumer. 3. How to use it. 4. Detailed comparison of BlockingQueue implementations.

JavaCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What It Is

A thread-safe blocking queue.

Characteristics:

  • First in, first out: Since it is a queue, it is naturally first in, first out.
  • Blocking: When inserting an element, if the queue is full, the insertion can block and wait until the queue is no longer full. When removing an element, if the queue is empty, the removal can block and wait until the queue is no longer empty.
  • Bounded or unbounded: This refers to the capacity of the queue. An unbounded queue is effectively bounded by Integer.MAX_VALUE.
  • Thread-safe.

2. Use Cases

Producer-consumer.

3. How to Use It

Method / Handling Throws Exception Returns Special Value Blocks Indefinitely Times Out
Insert add(e) offer(e) put(e) offer(e,time,unit)
Remove remove() poll() take() poll(time,unit)
Examine element() peek() Not available Not available

4. Detailed Comparison of Different BlockingQueue Implementations

ArrayBlockingQueue LinkedBlockingQueue PriorityBlockingQueue SynchronousQueue
Data structure Array Singly linked list Array (binary heap) Singly linked list
How blocking is implemented Lock + Condition Lock + Condition Lock + Condition CAS + LockSupport
Bounded / unbounded Bounded Bounded Unbounded Unbounded (does not store elements)
Throughput (using LinkedBlockingQueue as the baseline) Lower than LinkedBlockingQueue (read-read, read-write, and write-write block each other) / (read-read and write-write block each other; read-write do not block each other) Unbounded (read-read, read-write, and write-write block each other) Higher than LinkedBlockingQueue (a read and a write must match before they can proceed)

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub