• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

BlockingQueue Implementation

May 16, 2017 By j2eereference Leave a Comment

BlockingQueue :

java.util.concurrent.BlockingQueue is an interface that extends the java.util.Queue that add special support for blocking that it will wait for space to become available in the queue while storing and will wait for the queue to become non empty while retrieving elements.

Implementation of BlockingQueue :

  • util.concurrent.ArrayBlockingQueue : ArrayBlockingQueue is a fixed size bounded queue
  • util.concurrent.DelayQueue : The queue is unbounded and Elements added to the queue must implement thejava.util.concurrent.Delayed interface. Elements can be retrieved from the queue when the delay time has expired.
  • util.concurrent.LinkedBlockingQueue : LinkedBlockingQueue is an optionally-bounded blocking queue. This queue orders elements FIFO (first-in-first-out). The LinkedBlockingQueue keeps the elements internally in a linked structure
  • util.concurrent.PriorityBlockingQueue : A priority queue is unbounded queue where elements are ordered by natural order or by a Comparator provided at queue construction time .It does not permit null elements.
  • util.concurrent.SynchronousQueue : SynchronousQueue is a queue that can only contain a single element .In a SynchronousQueue an insert will wait for a remove operation by another thread and vice versa.

ArrayBlockingQueue implementation of BlockingQueue.

As already mentioned above, an ArrayBlockingQueue is a fixed size bounded queue. It is backed by array. As it is a BlockingQueue , its put(e) method will block a thread and waits for space to become available in the queue, and its take() method will block other thread and wait for an element become available in the queue. It is declared as given below

private static BlockingQueue<String> bq = new ArrayBlockingQueue<String>(no_of_element);

 Methods of ArrayBlockingQueue :

 put(E item) method in java –This method checks whether space is available or not.If space is not available it will wait else it will insert element and notify all waiting threads in java.

E take() method in java -This method Checks whether element is available or not.If element is not available it will wait else it will remove element and notify all waiting threads in java.

 Peek(): This method gets the element from head but not removed and returns null if not available

element(): This method gets the element from head but not removed and throw exception if not available

Example of ArrayBlockingQueue:

Java
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
 
public class BlockingQueueDemo {
   public static void main(String args[]){
      BlockingQueue<Integer> sharedQueue = new ArrayBlockingQueue<Integer>(5);
      Thread producerThread = new Thread(new ProducerThread(sharedQueue), "ProducerThread");
      Thread consumerThread = new Thread(new ConsumerThread(sharedQueue), "ConsumerThread");
      producerThread.start();
      consumerThread.start();
  }
}

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.concurrent.BlockingQueue;
 
class ConsumerThread implements Runnable{
      private BlockingQueue<Integer> sQueue;
      public ConsumerThread (BlockingQueue<Integer> sQueue) {
         this.sQueue = sQueue;
      }
 
      @Override
      public void run() {
       while(true){
         try {
              System.out.println("Consumer retrieved item : "+ sQueue.take());
             } catch (InterruptedException ex) {
            }
       }
      }
    }

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.concurrent.BlockingQueue;
 
class ProducerThread implements Runnable {
 
      private final BlockingQueue<Integer> sQueue;
      public ProducerThread(BlockingQueue<Integer> sQueue) {
         this.sQueue = sQueue;
      }
 
      @Override
      public void run() {
       for(int i=1; i<=5; i++){
        try {
              System.out.println("Producer produced item: " + i);
              sQueue.put(i);
            } catch (InterruptedException ex) {
            }
       }
     }
   }

Output:
Producer produced item: 1
Producer produced item: 2
Producer produced item: 3
Producer produced item: 4
Producer produced item: 5
Consumer retrieved item : 1
Consumer retrieved item : 2
Consumer retrieved item : 3
Consumer retrieved item : 4
Consumer retrieved item : 5

Realtime Use cases:
1) Realtime use case for BlockingQueue is Chat application in which messages are put into a queue. Produces will produce the messages from one end and consumer will consume messages.

2) ThreadPoolExecutor uses BlockingQueue to put executable task which get executed by worker threads.

3) A real world example could be an application-wide notification framework, which sends mails to the stakeholders at various points during the course of application usage.

Related Posts

  • UncaughtExceptionHandler in java
  • How to generate and resolve OutOfMemoryError?
  • Difference between Spring’s Singleton scope & Singleton Design pattern
  • How to stop a thread?
  • Interrupting a thread in java
  • What is ThreadLocal in Java ?
  • ArrayList custom Implementation
  • Difference between volatile and synchronized keyword?
  • How to write thread safe code?
  • How to avoid deadlock in java ?

Filed Under: Core Java

Reader Interactions

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.