Custom BlockingQueue implementation in java

Custom BlockingQueue in java

In this post, we will see how to create your own custom BlockingQueue.

This is one of the most asked java interview questions. You need to implement your own BlockingQueue. This question helps interviewer to get your understanding of multithreading concepts.

Here is simple implementation of BlockingQueue.

  • We will use array to store elements in BlockingQueue internally. Size of this array defines maximum number of  elements that can reside in BlockingQueue at a time.
  • We will use lock and conditions objects to create custom BlockingQueue.
  • While putting the element in the queue, if the queue is full, then the producer will wait for queue to empty.
  • While consuming element from the queue, if the queue is empty then the consumer will wait for the queue to get filled.

Create a class named CustomBlockingQueue.java

Create another main class which will use above CustomBLockingQueue.

We have created two Runnable classes, one for producer and another for consumer and created two threads using these runnables.

Producing – 1
Producing – 2
Producing – 3
Producing – 4
Producing – 5
Producing – 6
Consuming – 1
Consuming – 2
Consuming – 3
Consuming – 4
Consuming – 5
Consuming – 6
Producing – 7
Producing – 8
Producing – 9
Producing – 10
Consuming – 7
Consuming – 8
Consuming – 9
Consuming – 10

Output may vary for you but there can be only 6 elements at a time in the CustomBlockingQueue.
That’s all about Custom BlockingQueue implementation in java

Was this post helpful?

Leave a Reply

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