How to Implement BlockingQueue Interface in Java

Last updated on Jun 19,2023 1K Views

How to Implement BlockingQueue Interface in Java

edureka.co

A queue is an important aspect of any Programming language. Especially if we talk about Java. In this article, we will discuss the BlockingQueue Interface in Java in the following order:

 

What is a BlockingQueue Interface in Java?

A BlockingQueue Interface in Java 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.

BlockingQueue Interface in Java doesn’t accept null values and throw NullPointerException if you try to store the null value in the queue. Java BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.

Java Queue Class Diagram

Java Queue interface extends the Collection interface. The Collection interface extends the Iterable interface. Some of the frequently used Queue implementation classes are LinkedList, PriorityQueue, ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, PriorityBlockingQueue, etc.. AbstractQueue provides a skeletal implementation of the Queue interface to reduce the effort in implementing Queue.

Stay up-to-date with the latest Flutter features and best practices through our Flutter Course.

BlockingQueue Types

The BlockingQueue are two types:

Syntax:
BlockingQueue blocking queue = new LinkedBlockingDeque();

 

BlockingQueue blocking queue = new LinkedBlockingDeque(5);

 

Methods in BlockingQueue Interface

Modifier TypeMethod SyntaxUsed ForDescription
booleanadd(E e)Insertion

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

booleancontains(Object o)Examine

Returns true if this queue contains the specified element.

intdrainTo(Collection c)Retrieving or Removal

Removes all available elements from this queue and adds them to the given collection.

intdrainTo(Collection c, int maxElements)Retrieving or Removal

Removes at most the given number of available elements from this queue and adds them to the given collection.

booleanoffer(E e)Insertion

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.

booleanoffer(E e, long timeout, TimeUnit unit)Insertion

Inserts the specified element into this queue, waiting up to the specified wait time if necessary for space to become available.

Epoll(long timeout, TimeUnit unit)Retrieving or Removal

Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available.

voidput(E e)Insertion

Inserts the specified element into this queue, waiting if necessary for space to become available.

intremaining capacity()Examine

Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking, or Integer.MAX_VALUE if there is no intrinsic limit.

booleanremove(Object o)+Retrieving or Removal

Removes a single instance of the specified element from this queue, if it is present.

Etake()Retrieving or Removal

Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

 

BlockingQueue Interface in Java Example: Service

package com.journaldev.concurrency;

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.BlockingQueue;

public class ProducerConsumerService {

    public static void main(String[] args) {

        //Creating BlockingQueue of size 10

        BlockingQueue<Message> queue = new ArrayBlockingQueue<>(10);

        Producer producer = new Producer(queue);	

        Consumer consumer = new Consumer(queue);

        //starting producer to produce messages in queue

        new Thread(producer).start();

        //starting consumer to consume messages from queue

        new Thread(consumer).start();

        System.out.println("Producer and Consumer has been started");

    }

}

With this, we come to an end of the BlockingQueue Interface in Java article. I hope all your concepts are now clear.

Check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course are designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “BlockingQueue Interface in Java” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES