What is BlockingQueue in Java and how to implement it?

Last updated on Nov 26,2019 3.5K Views
Sr Research Analyst at Edureka. A techno freak who likes to explore... Sr Research Analyst at Edureka. A techno freak who likes to explore different technologies. Likes to follow the technology trends in market and write...

What is BlockingQueue in Java and how to implement it?

edureka.co

Java is extremely popular among programmers because of its comprehensive range of built-in features. Most of the times you will be having a dedicated solution for your problem even before it appears. Such an extremely useful and important part of Java Collections is the BlockingQueue interface in Java. Through the medium of this article, I will throw some light on BlockingQueue in Java and the methods to implement it.

Below are the topics covered in this article:

BlockingQueue Interface in Java

BlockingQueue in Java is an interface that was added in Java 1.5 along with a few other concurrent Utility classes such as ConcurrentHashMap, CopyOnWriteArrrayList, etc. BlockingQueue interface belongs to the java.util.concurrent package. This interface enhances flow control by activating blocking, in case a thread is trying to dequeue an empty queue or enqueue a full queue. In either case, this interface comes in handy. In simpler terms, suppose a thread is trying to add elements into an already full queue. At this point in the program, BlockingQueue will be invoked which will block that particular thread until another thread releases the queue to make space. This can be a result of either dequeuing of an element(s) of clearance of the entire queue. Similarly, BlockingQueue will be invoked to block a thread trying to dequeue an already empty queue until some other thread inserts or add an element into the empty queue.

While working with the BlockingQueue interface in Java, you must remember that it does not accept a null value. In case you try to do that it will instantly throw a NullPointerException. The below figure represents the working of the BlockingQueue interface in Java.

This interface is mainly used between Producer-Consumers as it is Thread-Safe. What I mean is BlockingQueue interface can be used to create a queue that can be shared by both the producer and the consumer

In order to work with BlockingQueue in Java, first, you need to get familiar with its types. Let me introduce you to them in the next section of this article.

Types of Constructors for BlockingQueue in Java

There are two types of constructors for BlockingQueue interface in Java:

BlockingQueue bq = new LinkedBlockingDeque();
BlockingQueue bq = new LinkedBlockingDeque(10);

Now that you are familiar with the ways to implement BlockingQueue in Java, let me list down a  few of its methods.

Methods in BlockingQueue Interface

MethodDescription
boolean add(E e)This method helps in inserting the specified element into this queue if there is space in the queue else it will throw an IllegalStateException
boolean contains(Object o)This method returns true if the queue contains the specified element
int drainTo(Collection<? super E> c)This method will remove all available elements from the queue and add them to the specified collection
int drainTo(Collection<? super E> c, int maxElements)This method will remove at the given number of available elements from the queue and add them into the specified collection
booloean offer(E e)This method will insert the specified element into the queue if it is not full and return true, else it will return false
boolean offer(E e, long timeout, TimeUnit unit)This method will insert the specified element into the queue. In case the queue is full, it will wait up to the specified wait time for the space to become available.
E poll(long timeout, TimeUnit unit)This method helps in retrieving and removing the head of the queue. In case the queue is empty, it will wait up to the specified wait time for an element to become available
void put(E e)This method will insert the specified element into the queue by waiting for space to become available n case the queue is full
int remainingCapacity()This method helps in returning the number of additional elements that this queue can ideally accept without getting blocked
boolean remove(Object o)This method will remove a single instance of the specified element from the queue only if it is present
E take()This method will help in retrieving and removing the head of the queue by waiting for an element become available, in case the queue is empty.

BlockingQueue Implementations

Here I will be implementing a simple example of BlockingQueue in Java where class EduProducer will be generating the data and insert it into a queue, simultaneously, another class, EduConsumer will remove the data from the same queue.

For this I will be creating 3 classes namely:

  1. EduProducer
  2. EduConsumer
  3. EdurekaMain

Let’s now create each of these classes one by one.

EduProducer.java

package edureka;

import java.util.concurrent.BlockingQueue;

public class EduProducer implements Runnable {
	
	private final BlockingQueue<Integer> queue;

    @Override
    public void run() {

        try {
            process();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

    }

    private void process() throws InterruptedException {

        // Put 10 ints into Queue
        for (int i = 0; i < 10; i++) {
            System.out.println("[Producer] Add : " + i);
            queue.put(i);
            System.out.println("[Producer] Queue's Remaining Capacity : " + queue.remainingCapacity());
            Thread.sleep(150);
        }

    }

   

	public EduProducer(BlockingQueue<Integer> queue) {
		        this.queue = queue;		    
	}

}

EduConsumer.java

package edureka;

import java.util.concurrent.BlockingQueue;

public class EduConsumer implements Runnable {
	private final BlockingQueue<Integer> queue;

    @Override
    public void run() {

        try {
            while (true) {
                Integer take = queue.take();
                process(take);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

    }

    private void process(Integer take) throws InterruptedException {
        System.out.println("[Consumer] Remove : " + take);
        Thread.sleep(500);
    }

    public EduConsumer(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }

}

EdurekaMain.java

package edureka;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class EdurekaMain {

	public static void main(String[] args) {
		
		BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);

        new Thread(new EduProducer(queue)).start();
        new Thread(new EduConsumer(queue)).start();

	}

}

Once you are done writing the code, execute the program to get the below output:

[Producer] Add : 0
[Consumer] Take : 0
[Producer] Queue's Remaining Capacity : 9
[Producer] Add : 1
[Producer] Queue's Remaining Capacity : 9
[Producer] Add : 2
[Producer] Queue's Remaining Capacity : 8
[Producer] Add : 3
[Producer] Queue's Remaining Capacity : 7
[Consumer] Take : 1
[Producer] Add : 4
[Producer] Queue's Remaining Capacity : 7
[Producer] Add : 5
[Producer] Queue's Remaining Capacity : 6
[Producer] Add : 6
[Producer] Queue's Remaining Capacity : 5
[Consumer] Take : 2
[Producer] Add : 7
[Producer] Queue's Remaining Capacity : 5
[Producer] Add : 8
[Producer] Queue's Remaining Capacity : 4
[Producer] Add : 9
[Producer] Queue's Remaining Capacity : 3
[Consumer] Take : 3
[Consumer] Take : 4
[Consumer] Take : 5
[Consumer] Take : 6
[Consumer] Take : 7
[Consumer] Take : 8
[Consumer] Take : 9

This brings us to the end of this article on BlockingQueue in Java. If you wish to learn Java in more detail you can refer to our other Java articles as well.

Now that you have understood basics of BlockingQueue in Java, check out the Java Certification 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 is 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 in Java” and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 11th May,2024

11th May

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 1st June,2024

1st June

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR UiPath Selectors Tutorial