Understanding Blocking Queue Simple Code

Try running the following java snippet  to understand blocking queue. In the example below,  the size of the blocking queue is 3 and we will try two use cases

  1. Access  3 elements using thread and  see the behavior.
  2. Access  4  elements using thread and  see the behavior.

In the second case , you will understand the behavior of blocking queue,  thread  will be blocked as the queue will be empty after accessing 3 elements.

Java Code Snippet

BlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<String>();
linkedBlockingQueue.add(“1”);
linkedBlockingQueue.add(“2”);
linkedBlockingQueue.add(“3”);

int n = 4;  // change this value to 3 and see the behavior.
Runnable r = ()->{
for(int i=0;i<n;i++){
try{
System.out.println(linkedBlockingQueue.take());
}catch(Exception exception){
exception.printStackTrace();
}
}

};
new Thread(r).start();

 

Leave a comment