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.
- The Array Blocking Queue
- The Delay Queue
- Linked Blocking Deque
- Linked Blocking Queue
- Linked Transfer Queue
- The Priority Blocking Queue
- 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:
- Addition of the elements
- Accessing the elements
- Deleting the elements
- 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.