BlockingQueue in java

BlockingQueue in java
BlockingQueue is introduced in java with concurrent package with ConcurrentHashMap. It is thread safe queue to put and take elements from it.
BlockingQueue is special type of queue which is used when one thread produces object and another thread consumes it.
Producer thread will keep inserting objects to queue until it reaches upper limit. Once this queue size has reached that limit then producer thread will get blocked and won’t able to put objects into queue until consumer thread starts consuming it.
Similarly consumer thread keep taking objects from queue until queue becomes empty. Once queue becomes empty, consumer thread get blocked and waits for producer threads for inserting objects into the queue.
If you put null to BlockingQueue, it will [NullPointerException]( “NullPointerException”) at run time.
It has two important methods
put : producer thread put objects into the queue until it reaches to the limit and waits for consumer thread to take out object after that.
take : consumer thread take out object from the queue until queue becomes empty. Once queue is empty, it waits for producer thread to put object into the queue.


In this example, we will see how to use BlockingQueue.
Create Producer thread which will create objects which will be consumed by Consumer thread.
Create Consumer thread which will consume objects.
Create main class which will start above two threads.
When you run above program , you will get following output:

Source code:

click to begin

20KB .zip

Was this post helpful?

Related Posts

  • ArrayBlockingQueue in java
    19 September

    ArrayBlockingQueue in java

    Table of ContentsWhat is BlockingQueueArrayBlockingQueueFeaturesConstructorsMethodsUsage ScenariosImplementation CodeSummary In this article, we will understand the Java concurrent queue, BlockingQueue. We will then go deep into it’s one of the implementation, ArrayBlockingQueue. What is BlockingQueue BlockingQueue interface was introduced in Java 5 under concurrent APIs and it represents a thread-safe queue in which elements can be added […]

  • Custom BlockingQueue in java
    16 October

    Custom BlockingQueue implementation 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 […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.