• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

How to Use Java BlockingQueue

August 31, 2023 //  by Talha Malik

The term queue refers to the data structures in which the element that is entered first comes out of the queue first. That means it obeys the FIFO principle. The blocking queue in Java has a feature that blocks the element from entering the queue if the queue is full and waits for the queue to get some elements so that the deletion takes place. The blocking queue has been found effective in solving the problems related to queues.

In this article, we will demonstrate in detail how to implement BlockingQueue in Java.

How to Use Java BlockingQueue?

The BlockingQueue in Java helps in blocking the relative operations and helps resolve issues related to the queues. The elements are blocked from entering if the queue is full. In the second scenario, the queue should not be null when removing an element. The queue must contain elements to delete. 

The blocking queue can be implemented using the below-mentioned classes:

  • ArrayBlockingQueue: This blockingqueue contains elements in the array.
  • LinkedListBlockingQueue: This blocking queue contains a linked list to perform different operations.
  • Priority Blocking Queue: This queue uses the priority class and implements the blocking operation on the queue.

Method 1: Using ArrayBlockingQueue()

The array BlockingQueue in Java uses an array of elements to perform various operations like accessing the elements and inserting and deleting the elements. The put() and remove() method helps in the insertion and deletion of elements from the respective array.

//import the package for the blockingqueue
import java.util.concurrent.BlockingQueue;
//Import array blocking queue to declare elements in the queue
import java.util.concurrent.ArrayBlockingQueue;
//Create a class for the blocking queue
class blockingqueue {
    public static void main(String[] args) {
        /Enter the capacity of the blocking queue
      BlockingQueue<String> num = new ArrayBlockingQueue<>(8);
      //Use try and catch block
      try {
        num.put("Intro");
        num.put("to");
        num.put("BlockingQueue");
       
        //Print the list of Strings in the blocking queue
        System.out.println("The String in the blocking queue are: " + num);
        // Remove Elements from the blocking queue
        String numberstoberemoved = num.remove();
        System.out.println("The String that has been removed from the queue is : " + numberstoberemoved);
      }
      catch(Exception n) {
          n.getStackTrace();
      }
    }
}

In the above code:

  • The packages related to BlockingQueue and ArrayBlockingQueue have been imported.
  • The elements have been added to the array using the put() method
  • An element in the array has been removed using the remove() method.
  • If the array is empty, an exception will be thrown.

Output

In the above output, the string that is “Intro” has been removed from the array using the method remove().

Method 2: Using LinkedBlockingQueue()

The linked list is used to provide a blocking interface to the elements in the queue. Two methods: put() and take() are implemented to add elements and remove the first element from the array.

/Import the package the for linked blocking queue
import java.util.concurrent.LinkedBlockingQueue;
//Create a class for the linked blocking queue
class linkedblockingqueue {
    public static void main(String[] args) {
        /Enter the capacity of the blocking queue
      LinkedBlockingQueue<Integer> num = new LinkedBlockingQueue<>(8);
      //Use try and catch block
      try {
        num.put(5);
        num.put(8);
        num.put(9);
        num.put(4);
        num.put(3);
        //Print the list of elements in the blocking queue
        System.out.println("The values in the blocking queue are: " + num);
        // Remove Elements the from blocking queue
        int numberstoberemoved = num.take();
        System.out.println("The number that has been removed from the queue is : " + numberstoberemoved);
      }
      catch(Exception n) {
          n.getStackTrace();
      }
    }
}

In the code above, 

  • The package for the LinkedBlockingQueue has been imported.
  • The elements are added to the array respectively.
  • The take() method is responsible for removing the element that is present at the head of the linked list.
  • The println() function has printed the results of the removed element.

Output

In the above output, the head of the queue which is 5 has been removed.

Method 3: Using PriorityBlockingQueue()

The priorityBlockingQueue() supports all the blocking rules. It is similar to the priority queue. Here are coding examples that will let you comprehend this concept better:

Example 1: PriorityBlockingQueue() on Strings 

In the following code, a priority blocking queue is declared along with the elements. The output will print the results according to the priority.

//Import the Java package for blocking the queue
import java.util.concurrent.PriorityBlockingQueue;
//Create a Class for the functions to be declared.
public class priorityblocking{
public static void main(String[] args)
{
    //Create a String declared in the priority Blocking queue
PriorityBlockingQueue<String> addstr
= new PriorityBlockingQueue<String>();
//Enter Strings
addstr.add("Hello");
addstr.add("to");
addstr.add("Java");
addstr.add("Programming");
// Print queue
System.out.println("The elements in the PriorityBlockingQueue are : \n" + addstr);
}
}

Output

In the below output, the results have been printed according to the priority.

Example 2: PriorityBlockingQueue() on Integers.

In the code below the integers are declared in the PriorityBlockingQueue and the code is the same as the previous.

//Import the Java package for blocking the queue
import java.util.concurrent.PriorityBlockingQueue;

//Create a Class for the functions to be declared.
class priorityblocking {
    public static void main(String[] args) {
        // Create a String declared in the priority Blocking queue
        PriorityBlockingQueue<Integer> addInt = new PriorityBlockingQueue<Integer>();
        // Enter Strings
        addInt.add(10);
        addInt.add(25);
        addInt.add(8);
        addInt.add(3);
        // Print queue
        System.out.println("The elements in the PriorityBlockingQueue are : \n" + addInt);
    }
}

Output

In the following output, the integer values have been printed according to the priority. 

This sums up the implementation of BlockinQueue in Java using different classes.

Conclusion

The Java BlockingQueue blocks the element from entering the queue if the queue is full and for deletion, it requires at least one element to be present otherwise it throws the exception. In this write-up, we have discussed in detail the implementation of Blockingqueue in Java.

Category: Java

Previous Post: « How to Measure Execution Time with System.currentTimeMillis() in Java
Next Post: How to Implement ActionListener in Java »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Use Optional.ofNullable() Method in Java

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact