Write code to implement a blocking queue in Java.

By | March 6, 2023

Here’s an implementation of a blocking queue in Java using the built-in java.util.concurrent package:

import java.util.concurrent.ArrayBlockingQueue;

public class BlockingQueueExample {

  private final ArrayBlockingQueue<Integer> queue;

 

  public BlockingQueueExample() {

    // Initialize the queue with a capacity of 10

    this.queue = new ArrayBlockingQueue<>(10);

  }

  public void enqueue(Integer item) throws InterruptedException {

    // Add the item to the queue

    queue.put(item);

  }

  public Integer dequeue() throws InterruptedException {

    // Remove and return the first item from the queue

    return queue.take();

  }

}

This implementation uses an ArrayBlockingQueue with a fixed capacity of 10. The enqueue method adds an item to the end of the queue using the put method, which will block if the queue is full. The dequeue method removes and returns the first item from the queue using the take method, which will block if the queue is empty.

Note that ArrayBlockingQueue is a thread-safe implementation of the BlockingQueue interface, so we don’t need to add any additional synchronization code to make the queue thread-safe.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *