×

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 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

How to find characters with the maximum number of times in a string java

Problem statement In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create...

3 minutes read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.

Java Continue Keyword

The java keyword ‘continues’ has also been called as java continue statement.The main concepts of the java continue statement or keyword is used in the controlling of the loop structure.Java...

3 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Java Boolean getBoolean() Method

The getBoolean() method of Java Boolean class returns true if the specified system property is not null and is equal to the String ‘true’, else the result returned is false. Syntax public...

1 minute read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.