×

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from the back of the lists and removed at the front. As a result, it is also claimed that the queue is established on the FIFO (First-In-First-Out) concept.

Blocking Queue is indeed a queue that also enables operations that watch for the queue to stop being empty when retrieving an element and watch for the slot to be empty when inserting an element into the queue. In addition to other concurrent utility classes, Java 1.5 offers support for the Blocking Queue interface. is indeed a Java queue which supports activities such as retrieving and removing elements only after the queue has stopped being empty, and adding elements only after there is room in the queue.

If you try to store a null value in a Java Blocking Queue, it will fail with a NullPointerException. Implementations of the blocking queue in Java are thread-safe. All queuing techniques employ inner locks or other types of concurrency control and are atomic in nature. The Java Blocking Queue interface, which is a component of the Java Collections Framework, is mostly used to implement producer-consumer problems. We don't need to be concerned about having to wait for the producer space or the consumer object to become available in the Blocking Queue because Blocking Queue implementation classes take care of that. ArrayBlockingQueue, Linked Blocking Queue, Priority Blocking Queue, Synchronous Queue, and other implementations of Blocking Queue are available in Java. We will utilise an implementation of Array Blocking Queue to implement the producer-consumer problem. Here are some crucial techniques you need to be aware of.

Several crucial details regarding the blocking queue

  • There may be a remaining Capacity in a blocking queue above which we are unable to input another element without blocking.
  • Thread safety is guaranteed across all Blocking Queue implementations. Each technique uses internal locks or some other type of concurrency control to accomplish its goals.
  • Null elements are not accepted by a blocking queue. A NullPointerException is thrown by the implementation if we attempt to add a null value.
  • Blocking Queue implementations are available in Java 5's java.util.concurrent package.

Classes for Implementing a Blocking Queue

Since the Blocking Queue is an interface, there is no mechanism for directly giving an instance of it; therefore, in order to implement the Blocking Queue, classes implementing it must be created.

  1. The Array Blocking Queue
  2. The Delay Queue
  3. Linked Blocking Deque
  4. Linked Blocking Queue
  5. Linked Transfer Queue
  6. The Priority Blocking Queue
  7. The Synchronous Queue

The classes utilised to implement the Blocking  Deque class are Linked Blocking Queue and Array Blocking Queue. These two classes are made up of the Blocking Deque and array and Blocking Deque as well as linked list data structures, respectively.

Use of Blocking Queue syntax:

The java.util.concurrent.BlockingQueue package and the aforementioned classes are imported using the import line.

import java.util.concurrent.BlockingQueue ;  
                   or  
import java.util.concurrent.* ;  

establishing a blocking queue

public interface BlockingQueue< E > extends Queue< E >

The Blocking Queue Interface's methods

In the process of implementing Blocking Queue, methods are divided into three categories:

1. Techniques that throw exceptions

  • add(): The Blocking Queue has a new element added toward the end using the add() method. When the queue is full, it throws an exception.
  • element(): This function returns the first item in the queue. If somehow the queue is empty, it raises an exception.
  • remove(): The remove() method eliminates a component from the blocking queue. If somehow the queue is empty, it raises an exception.

2. methods with a value return

  • offer(): This function adds a specified element at the end of the Blocking Queue. If somehow the queue is full, it returns false. The technique is also compatible with timeouts, allowing for the passage of time units as a parameter.
    For instance: 
offer( val, 10, ms) ; 

The Blocking Queue will receive an element using the aforementioned mechanism for 100 milliseconds. The function returns false if somehow the item cannot be added in 10 ms.

  • peek(): It gives the Blocking Queue head or top. Whenever the queue is empty, it returns null.
  • Pop(): A blocker is taken out of the blocking queue using the poll() function. Should the queue be empty, it returns null. Additionally, it can be employed with timeouts, allowing for the parameterization of time units.

3. Techniques that interrupt the operation

  • Put(): The put() function adds a new item to the blocking queue. The put() function pauses to insert one element if somehow the queue is already full before continuing if there is still room.
  • take(): eliminates and returns a block of elements from the blocking queue. When the list is empty, the take() function waits until some elements are available in the queue for deletion.

Types of Blocking Queue

Blocking Queue comes in two varieties:

  • Unbounded Queue: An unrestrained blocking queue is one whose size is infinitely expandable and so never blocks. The BlockingQueue's capacity will be set to an integer value. MAX VALUE. The Unbounded queue becomes bigger as the components are added.

Syntax:

BlockingQueue bq = new LinkedBlockingDeque( ) ;
  • Bounded Queue: The bounded queue is yet another variety of blocking queue. You can make one by giving the queue's capacity to the queue's constructor.

Syntax:

// Building a blocking queue with a capacity of 100 that is bounded in nature.
BlockingQueue bq = new LinkedBlockingDeque( 100 ) ;  

Example 1:

As an illustration of the Blocking Queue idea, let's look at an example.

// Java may support Blocking Queue by importing certain libraries.
import java.util.concur.BlockingQueue ;  
import java.util.concur.ArrayBlockingQueue ;  
public class khan {  
    public static void main( String[ ] args ) {  
      // utilising ArrayBlockingQueue to declare a Blocking Queue of a "bounded" type
      BlockingQueue< String > alpha = new ArrayBlockingQueue< >( 8 ) ;  
      try {  
        // add a component to the blocking queue
        alpha.put( " Z " ) ;  
        alpha.put( " Y " ) ;  
        alpha.put( " X " ) ;  
        alpha.put( " W " ) ;  
        alpha.put( " V " ) ;  
        alpha.put( " U " ) ;  
        alpha.put( " T " ) ;
        alpha.put( " S " ) ;    
        System.out.println( " The BLockingQueue's content : " + alpha ) ;  
        // removing a few items from the queue
        String tempa = alpha.taken( ) ;   
        System.out.println( " The omitted number is : " + tempa ) ;  
        // After removing a single piece, blocking queue
        System.out.println( " Once one piece is deleted, the content of the blocking queue : " + alpha ) ;  
      }  
      catch( Exception e ) {  
          e.getStackTrace( ) ;  
      }  
    }  
}  

Output:

The BLockingQueue's content : [ Z , Y , X , W , V , U , T , S ]
The omitted number is : Z
Once one piece is deleted, the content of the blocking queue : [ Y , X , W , V , U , T , S ]

Basic Procedures

Let's take a more thorough look at the various activities that may be carried out on the Blocking Queue:

  1. Addition of the elements
  2. Accessing the elements
  3. Deleting the elements
  4. Iterating through elements

Addition of the elements

Depending on the kind of structure we want to utilise a "Linked Blocked Deque" as, we may put pieces into it in a variety of ways. The "add()" function is the one that is most frequently were using to add elements to the deque's tail. For adding a whole collection of elements to Linked Blocking Deque, there is another function called "addAll()". Add functions like "add()" and "put()" to the application so as to utilize the deque as either a queue.

Alpha.java

import java.util.concur.LinkBlockDeque ;  
import java.util.concur.BlockingQueue ;  
import java.util.* ;  
public class alpha {  
    public static void main( String[ ] args )  
        throws IllegalStateException  
    {  
        // constructing a class object of Blocking Queue
        BlockingQueue< String > alpha  
            = new LinkBlockDeque< String >( ) ;  
        // By utilising the add() function, alphabets are added to the Blocking Queue.
        alpha.add( " Z " ) ;  
        alpha.add( " Y " ) ;  
        alpha.add( " X " ) ;  
        alpha.add( " W " ) ;  
        alpha.add( " V " ) ;      
        BlockingQueue< String > alpha3  
            = new LinkBlockDeque< String >( ) ;  
        // adding collection of elements using addAll( ) method  
        alpha3.addAll( alpha ) ;  
        // before erasing the print BlockingQueue
        System.out.println( " Blocking Queue's contents are :" + alpha ) ;  
        System.out.println( " another blocking queue's contents :" + alpha3 ) ;  
    }   
}  

Output:

Blocking Queue's contents are : [ Z , Y , X , W , V ]
another blocking queue's contents : [ Z , Y , X , W , V ]

Accessing the elements

Using methods such as contains(), element(), peek(), and poll(), we can acquire the items of the "LinkedBlockingDeque".

Fun.java

import java.util.concur.* ;  
public class fun {  
     public static void main( String[ ] args )  
    {  
         // generating a Linked Blocking Deque object of the desired kind 
        BlockingQueue< String > alpha1  
            = new LinkedBlockingDeque< String >( ) ;  
   
        // utilising the add() function, adding entries to the BlockingQueue
        alpha.add( " Z " ) ;  
        alpha.add( " Y " ) ;  
        alpha.add( " X " ) ;  
        alpha.add( " W " ) ;  
        alpha.add( " V " ) ;      
        // the Blocking Queue's component parts are printed.
        System.out.println(  
            " The Linked Blocking Queue's items are : " ) ;  
        System.out.println( alpha ) ;  
        // obtaining the alphabetic element "X" from the queue
        if ( alpha.contains( " X " ) )  
            System.out.println(  
                " Hey! Successfully founded Element X is in the queue " ) ;  
        else  
            System.out.println( " There is no such element in the queue." ) ;  
   
        // use the function element ( ) to get the queue's first member
        String peak = alpha.element( ) ;  
        System.out.println( " The element at the peak of the queue is : " + peak ) ;  
    }  
}

Output:

The Linked Blocking Queue's items are : [ Z , Y , X , W , V ]
Hey! Successfully founded Element X is in the queue
The element at the peak of the queue is : Z

Deleting the elements

A LinkedBlockingDeque can have elements removed from it by using the remove command (). The first and last components can also be removed using other methods like take() and poll().

Fun.java

import java.util.concur.* ;  
public class fun {  
    public static void main( String[] args )  
    {  
        // generating a Linked Blocking Deque object of the desired kind 
        BlockingQueue< String > alpha  
            = new LinkedBlockingDeque< String >( ) ;  
        // utilising the add() function, adding the entries to the BlockingQueue
        alpha.add( " Z " ) ;  
        alpha.add( " Y " ) ;  
        alpha.add( " X " ) ;  
        alpha.add( " W " ) ;  
        alpha.add( " V " ) ;      
        // printing the blocked queue's component parts
        System.out.println(  
            " The following is the content of LinkedBlockingDeque : " ) ;  
        System.out.println( alpha ) ;  
        // Using the remove() method, delete the entries from the queue.
        alph.remove( " X " ) ;  
        alph.remove( " V " ) ;  
        // Let's explore what happens if we attempt to delete an entry from the queue that doesn't truly exist.
        alpha.remove( " D " ) ;  
        // Print the elements of the alpha object of Blocking Queue  
        System.out.println(  
            " After components are removed, this is the contents of the LinkedBlockingDeque : " ) ;  
        System.out.println( alpha ) ;  
    }  
}  

Output:

The following is the content of LinkedBlockingDeque : [ Z , Y , X , W , V ]
After components are removed, this is the contents of the LinkedBlockingDeque : [ Z , Y , W ]

Iterating through elements

We may build an iterator and utilise the methods of either the Iterable interface, the foundation of the Java Collection Framework, to access the elements of a "Linked Blocking Deque" in addition to iterate through them. Any collection's element is returned using the Iterable "next()" function.

Blocking Queue Methods Behaviour

For inserting, removal, and inspect operation on the Blocking queue, Blocking Queue offers a number of methods. If the required action is not immediately completed, those four sets of techniques each respond differently.

  • Throws Exception: An exception is going to throw if the specified operation is not completed right away.
  • The special value: If the operation is not immediately fulfilled, some special value is returned.
  • Blocks: If the attempted action is not immediately successful, the approach call is blocked and it waits till it is.
  • Timeout: To ascertain if the procedure was successful or not, the special number is returned. The method calls that blocks until the required action occurs, but it does not wait for longer than the provided amount of time if it does not happen immediately.

Related Topics

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the...

3 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.