Javatpoint Logo
Javatpoint Logo

BlockingQueue in Java

Before directly jumping to the topic 'Blocking Queue' let us first understand Queue in brief. Queue is an ordered list of objects where insertions take place at the rear end of the list and deletion of elements takes place from the front end. Therefore, it is also said that Queue is based on FIFO ( First-In-First-Out ) principle.

BlockingQueue is a queue that additionally supports operations that wait for the queue to become non-empty when we are trying to retrieve an element, and wait for the space to be empty when an element is to be inserted in the queue. Java 1.5 provides support for BlockingQueue interface along with other concurrent utility classes.

Some important points with respect to the Blocking Queue :

  • A BlockingQueue may have a remainingCapacity beyond which we cannot insert any element without blocking.
  • All the implementations related to the BlockingQueue are thread-safe. All the methods achieve their events using internal locks or other forms of concurrency control.
  • A BlockingQueue does not accept null elements. If we try to add a null value the implementation throws a NullPointerException.
  • Java 5 provides the BlockingQueue implementations in the java.util.concurrent package.

BlockingQueue Implementing Classes

There is no provision of directly providing an instance of the BlockingQueue since it as an interface, so to implement BlockingQueue we need to create classes implementing it.

  1. ArrayBlockingQueue
  2. DelayQueue
  3. LinkedBlockingDeque
  4. LinkedBlockingQueue
  5. LinkedTransferQueue
  6. PriorityBlockingQueue
  7. SynchronousQueue

LinkedBlockingQueue and ArrayBlockingQueue are the classes used to implement BlockingDeque class. These two classes are a composition of BlockingDeque and linked list data structure and BlockingDeque and array respectively.

Syntax of using BlockingQueue :

We make use of import statement in order to use the above classes and import java.util.concurrent.BlockingQueue package.

Declaring a BlockingQueue

Creating objects of BlockingQueue class using LinkedBlockingDeque

Creating objects of BlockingQueue class using ArrayBlockingQueue

Methods of the BlockingQueue Interface

There are three categories of methods used in the implementation of BlockingQueue :

1. Methods that throw an exception

  1. add( ): It inserts an element to the BlockingQueue at the end of the queue. It throws an exception when the queue is full.
  2. element( ): It returns the top or the head of the queue. It throws an exception if the queue is empty.
  3. remove( ): It removes an element from the BlockingQueue. It throws an exception if the queue is empty.

2. Methods that return some value

i. offer( ): It inserts the specific element to the BlockingQueue at the rear end of the queue. It returns false if the queue is full. The method can also be used with timeouts, that is time units can be passed as a parameter.

For example:

Here, value is the element to be inserted in the queue. The above method will insert an element to the BlockingQueue for 100 milliseconds. If the element cannot be inserted in 100 milliseconds, the method returns false.

ii. peek( ): It returns the top or head of the BlockingQueue. It returns null if the queue is empty.

iii. poll( ): It removes an element from the BlockingQueue. It returns null if the queue is empty. It can also be used with timeouts, that is time units can be passed as a parameter.

3. Methods that block the operation

  1. i. put( ): The method inserts an element to the BlockingQueue. If in case the queue is full, the put( ) method waits until the queue has some vacant space to insert an element.
  2. ii. take( ): The method removes and returns an element from the BlockingQueue. If in case the queue is empty, the take( ) method waits until the queue has some elements to be deleted.

BlockingQueue Types

There are two types of BlockingQueue:

1. Unbounded Queue: Unbounded blocking queue is the queue that never blocks because its size could be grown to a very large size. The capacity of the BlockingQueue will be set to Integer.MAX_VALUE. When the elements are added, the size of the Unbounded queue grows.

Syntax :

2. Bounded Queue: Another type of the blocking queue is the bounded queue. It can be created by passing the capacity of the queue to the constructor of the queue.

Syntax :

Example :

Let us consider an example that explains the concept of BlockingQueue.

Output:

Content of BLockingQueue : [ A ,  B ,  C ,  D ,  E ,  F ,  G ]
The number removed is :  A 
Content of BLockingQueue after deleting one element : [ B ,  C ,  D ,  E ,  F ,  G ]    

Basic Operations

Let us have a broader look over different operations that can be performed on BlockingQueue :

  1. Adding elements
  2. Accessing elements
  3. Deleting elements
  4. Iterating through the elements

1. Adding Elements

We can add elements into a ' LinkedBlockedDeque ' in different ways depending on the type of structure we are trying to use it as. The most common method used to add elements in the rear end of the deque is the ' add( ) ' method. There is another function named ' addAll( ) ' method to add an entire collection of the elements to LinkedBlockingDeque. In order to use the deque as a queue function like ' add( ) ' and ' put( ) ' can be added in the program.

Example :

Output:

 Contents of Blocking Queue : [ A ,  B ,  C ,  D ,  E ]
 Contents of another Blocking Queue : [ A ,  B ,  C ,  D ,  E ]    

2. Accessing Elements

We can access the elements of the ' LinkedBlockingDeque ' using methods like contains( ), element( ), peek( ), poll( ).

Example :

Output:

The contents of the Linked Blocking Queue is : 
   [ A ,  B ,  C ,  D ,  E ]
   Yayy! Element C successfully founded in the queue 
   The top element of the queue is :  A   

3. Deleting Elements

Elements can be deleted from a LinkedBlockingDeque using remove(). Other methods such as take( ) and poll( ) can also be used in a way to remove the first and the last elements.

Example :

Output:

The content of LinkedBlockingDeque is : 
    [ A ,  B ,  C ,  D ,  E ]
    The content of the LinkedBlockingDeque after removing elements is : 
    [ A ,  B ,  D ]  

4. Iterating through the Elements

In order to iterate through the elements of a ' LinkedBlockingDeque ' we can create an iterator and use the methods of the Iterable interface, which is the root of the Collection Framework of Java, to access the elements. The ' next( ) ' method of Iterable returns the element of any collection.

Output:

The content of the Linked Blocking Deque is : 
 A   B   C   D   E      

BlockingQueue Methods

Method Description
boolean add( E e ) It inserts the specified element into the specified queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
boolean contains( Object o ) It returns true if this queue contains the specified element.
int drainTo( Collection< ? super E > c ) It removes all available elements from this queue and adds them to the given collection.
int drainTo( Collection< ? super E > c, int maxElements ) It removes at most the given number of available elements from this queue and adds them to the given collection.
boolean offer( E e ) It inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
boolean offer( E e, long timeout, TimeUnit unit ) It inserts the specified element into this queue, waiting up to the specified wait time if necessary, for space to become available.
E poll( long timeout, TimeUnit unit ) It retrieves and removes the head of this queue, waiting up to the specified wait time if necessary, for an element to become available.
void put( E e ) It inserts the specified element into this queue, waiting if necessary, for space to become available.
int remainingCapacity( ) It returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking, or Integer.MAX_VALUE if there is no intrinsic limit.
boolean remove( Object o ) It removes a single instance of the specified element from this queue, if it is present.
E take( ) It retrieves and removes the head of this queue, waiting if necessary, until an element becomes available.

The Behavior of BlockingQueue Methods :

BlockingQueue provides certain methods for insertion, removal, and examine operations on the Blocking queue. Each of the four sets of methods behaves differently if the requested operation is not satisfied immediately.

  1. Throws Exception : If the requested operation is not satisfied immediately, an exception will be thrown.
  2. Special value : A special value is returned if the operation is not satisfied immediately.
  3. Blocks : The method call is blocked if the attempted operation is not satisfied immediately and it waits until it gets executed.
  4. Times out : The special value is returned to determine whether the operation was successful or not. If the requested operation does not happen immediately, the method calls for blocks until it occurs, but does not wait for more than the specified time.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA