01 July, 2019

Top 5 interview questions on BlockingQueue


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). 



Follow for more details on @Facebook!!!


Find More Questions & Answers Below.

No comments:

Post a Comment