Showing posts with label Threading. Show all posts
Showing posts with label Threading. Show all posts

Monday, September 7, 2026

Top 5 Interview Questions on BlockingQueue in Java


1) What is BlockingQueue ? Under which package of JDK its available ?

Ans- A blocking queue is an interface. BlockingQueue implementations are thread-safe. It helps to handle multi threaded execution , specially its for producer and consumer problem.
The 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. 

There are few implementation for this BlockingQueue as below, all these classes available under java.util.concurrent package.
  • ArrayBlockingQueue
  • SyncronousBlockingQueue
  • PriorityBlockingQueue
  • LinkedBlockingQueue
  • DelayQueue

2) What is the use of these methods peek(), poll(), take() and remove() ?

Ans - 
peek() :- This retrieves, but does not remove, the head of this queue,or returns null if this queue is empty. It doesn't throw any exception.

poll() :- This retrieves and removes the head of this queue,or returns null if this queue is empty.It doesn't throw any exception.

take() :- This retrieves and removes the head of this queue, waiting if necessary until an element becomes available. This method waits for certain time , if its interrupted then it throws InterruptedException. 

remove() :- This retrieves and removes the head of this queue. This method differs from poll() only in that it throws an exception (NoSuchElementException ) if this queue is empty.

Apart from the above difference take() method is provided by BlockingQueue i.e. java.util.concurrent.BlockingQueue.take(). Where as other methods provided by Queue i.e.  java.util.Queue.poll(), java.util.Queue.peek(), java.util.Queue.remove()


3) Is this possible to declare BlockingQueue implementation with ZERO/0 size?

Ans- Yes, if its unbounded implementation. But,if its bounded then we have to provide a capacity. The capacity must be greater than ZERO (i.e. capacity > 0).If we create a BlockingQueue with ZERO capacity then this will throw java.lang.IllegalArgumentException.

4) Write a program for demonstrating producer & consumer problem using blocking
 queue.

Ans- Find the answer here.

5) What is the difference between ArrayBlockingQueue and LinkedBlockingQueue ?

Ans- ArrayBlockingQueue is a bounded blocking queue backed by an array of objects. LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. 
Linked queues typically have higher throughput than array-based queues but less predictable performance in most concurrent applications.Linked nodes are dynamically 
created upon each insertion unless this would bring the queue capacity (Integer.MAX_VALUE). 

Monday, July 1, 2019

Producer Consumer Example Using BlockingQueue in Java

Threading is a very tricky and interesting concept in java programming language. There are many problems we face in technology out of which producer-consumer is one. Today we will write a java program for showing producer consumer problem and its solution by using BlockingQueue implementation. 

In this program we will use ArrayBlockingQueue

FoodProducer.java

package com.techbyteslearn.lab.concurrent; import java.util.concurrent.BlockingQueue; public class FoodProducer implements Runnable { private BlockingQueue<String> producerQueue = null; public FoodProducer(BlockingQueue<String> queue) { producerQueue = queue; } @Override public void run() { try { producerQueue.put("Drinks"); Thread.sleep(2000); producerQueue.put("Chocolates"); Thread.sleep(2000); producerQueue.put("Fruits"); Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } } }

 

FoodConsumer.java

 

package com.techbyteslearn.lab.concurrent;

import java.util.concurrent.BlockingQueue;

public class FoodConsumer implements Runnable {

    private BlockingQueue<String> consumerQueue = null;

    public FoodConsumer(BlockingQueue<String> consumerQueue) {
        this.consumerQueue = consumerQueue;
    }

    @Override
    public void run() {
        try {
            System.out.println(consumerQueue.take());
            System.out.println(consumerQueue.take());
            System.out.println(consumerQueue.take());

            Thread.sleep(2000);

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

 

MainFoodProcess.java

 

package com.techbyteslearn.lab.concurrent; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class MainFoodProcess { public static void main(String[] args) throws InterruptedException { final BlockingQueue<String> queue = new ArrayBlockingQueue<>(2); FoodProducer producer = new FoodProducer(queue); FoodConsumer consumer = new FoodConsumer(queue); new Thread(producer).start(); new Thread(consumer).start(); Thread.sleep(3000); } }

Output:

Drinks 
Chocolates 
Fruits
The important point in this example is that the ArrayBlockingQueue has a capacity of 2, while the producer adds three items. The put() method blocks when the queue is full until the consumer takes an item from the queue.

The output here is that, every time the producer insert element into the Queue the consumer will take that element out of the queue. 

Here we have used the below 2 important methods take() and put(). There are few many method provided by the BlockingQueue implementation. Find more methods on BlockingQueue.

take() - Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.
put() - Inserts the specified element into this queue, waiting if necessary for space to become available.


Happy Learning.