{{announcement.body}}
{{announcement.title}}

Java Concurrency: Blocking Queues

DZone 's Guide to

Java Concurrency: Blocking Queues

Learn more about Java's BlockingQueue and the theory behind it in this simple code demonstration.

· Java Zone ·
Free Resource

code on laptop

Learn more about Java's BlockingQueue and the theory behind it in this simple code demonstration.

A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full. A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue. A thread trying to enqueue an item in a full queue is blocked until some other thread makes space in the queue, either by dequeuing one or more items or clearing the queue completely.

Java 5 comes with blocking queue implementations in the java.util.concurrent package. Yet, it can be useful to know the theory behind their implementation.

Blocking Queue Implementation

The implementation of a blocking queue looks similar to a Bounded Semaphore. Here is a simple implementation of a blocking queue:

public class BlockingQueue {
 private List queue = new LinkedList();
 private int limit = 10;
 public BlockingQueue(int limit) {
  this.limit = limit;
 }
 public synchronized void enqueue(Object item) throws InterruptedException {
  while (this.queue.size() == this.limit) {
   wait();
  }
  if (this.queue.size() == 0) {
   notifyAll();
  }
  this.queue.add(item);
 }
 public synchronized Object dequeue() throws InterruptedException {
  while (this.queue.size() == 0) {
   wait();
  }
  if (this.queue.size() == this.limit) {
   notifyAll();
  }
  return this.queue.remove(0);
 }
}


Notice how notifyAll() is only called from enqueue() and dequeue() if the queue size is equal to the size bounds (0 or limit). If the queue size is not equal to either bound when enqueue() or dequeue() is called, there can be no threads waiting to either enqueue or dequeue items.

This text is part of my tutorial on Java Concurrency which now contains 19 texts.



If you enjoyed this article and want to learn more about Java Collections, check out this collection of tutorials and articles on all things Java Collections.

Topics:
java ,java concurrency multithreading blocking queue ,concurrency ,blockingqueue ,queue ,collections

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}