×

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 Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 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.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.