Blocking Queue

  • Eclipse: Oxygen
  • Java: 1.8

The blocking queue is used as a container for objects when the threads are inserting the objects and other threads are taking the objects out of it. The threads can only continue inserting the objects until a specific limit and take out or use the resources until a specific limit. Therefore, any limit reached the blocking queue will immediately block the threads.

The following program will demonstrate the capability of blocking queue. In order to understand the concept of blocking queue, we will start with the producer and consumer. As the name suggests producer thread add the element in the queue and consumer thread consumes the element from the queue. These two thread works simultaneously on blocking queue collection.

We have created a producer class which implements the Runnable interface. Producer class will use the put() method to add elements in the queue and before putting new element the thread will wait for one second.

Once the element in blocking queue reached to the maximum limit, instead of terminating the program blocking queue will force the thread to wait until there is an empty space.

Output

Value added in the queue: 1

Value added in the queue: 2

Value added in the queue: 3

Value added in the queue: 4

Value added in the queue: 5

Value added in the queue: 6

Value added in the queue: 7

Value added in the queue: 8

Value added in the queue: 9

Value added in the queue: 10

Now we will add consumer class which will consume element from the blocking queue. Consumer class will use the take() method to consume the elements from the blocking queue..

As the thread timer for producer class is one second and consumer class is of five seconds so every second an element will be added to the queue and in every five seconds an element will be removed from the queue. As soon as the adding element reaches to the max capacity the blocking queue force thread to wait for the empty space and when the element is deleted by the consumer class, a new element is added.

Output

Value added in the queue: 1

Value added in the queue: 2

Value added in the queue: 3

Value added in the queue: 4

Value removed in the queue: 3

Value added in the queue: 4

Value added in the queue: 5

Value added in the queue: 6

Value added in the queue: 7

Value added in the queue: 8

Value removed in the queue: 7

Value added in the queue: 8

Value added in the queue: 9

Value added in the queue: 10

Value removed in the queue: 10

Value added in the queue: 10

Value removed in the queue: 10

Value added in the queue: 10

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu