×

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

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Hogben Numbers in Java

In this section, we will discover what the Hogben number is and develop Java programs that compute it. Java coding interviews and academic exams typically involve questions about the Hogben...

3 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.