Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
ConcurrentLinkedQueue in Java
2.1.
Hierarchy of ConcurrentLinkedQueue Class in Java
2.2.
Constructors of ConcurrentLinkedQueue class in Java
3.
Methods of ConcurrentLinkedQueue in Java
4.
Basic Operations
4.1.
Addition of Elements
4.2.
Accessing the Elements
4.3.
Removing Elements
4.4.
Iterating through the ConcurrentLinkedQueue
5.
Frequently Asked Questions
6.
Conclusions
Last Updated: Mar 27, 2024
Easy

ConcurrentLinkedQueue Class and its Methods

Author Sanjana Yadav
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

The Java Collection Framework includes the ConcurrentLinkedQueue class. It is part of the java.util.concurrent package. It was first included in JDK 1.5. It is used to implement Queue simultaneously with the help of LinkedList. It is a thread-safe unbounded Queue implementation that inserts entries at the tail of the Queue in a FIFO (first-in-first-out) way. It is useful when several threads share an unbounded Queue. Null elements are not permitted in this class. Iterators are inconsistent. This class and its iterator implement all of the Queue and Iterator interfaces' optional methods.

ConcurrentLinkedQueue in Java

Hierarchy of ConcurrentLinkedQueue Class in Java

java.lang.Object
  ↳ java.util.AbstractCollection<E>
     ↳ java.util.AbstractQueue<E>
        ↳ Class ConcurrentLinkedQueue<E>

Constructors of ConcurrentLinkedQueue class in Java

ConcurrentLinkedQueue(): constructs an empty queue. 

Syntax

ConcurrentLinkedQueue<E> clq = new ConcurrentLinkedQueue<E>();


ConcurrentLinkedQueue(Collection<E> cln): constructs a queue with the elements of the Collection passed as the parameter.

Syntax

ConcurrentLinkedQueue<E> clq = new ConcurrentLinkedQueue<E>(Collection<E> cln);

Also see,  Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Methods of ConcurrentLinkedQueue in Java

The ConcurrentLinkedQueue class and its iterator implement all of the Queue and Iterator interfaces' optional methods.

  1. add(): This function adds the specified element to the end of the queue.
     
  2. addAll(): Adds all of the elements from the specified collection to the tail of the queue.
     
  3. contains(): If the queue has the specified element, this function returns true.
     
  4. forEach(): Executes the specified action on each element until all items have been processed.
     
  5. isEmpty(): Returns true if the queue is empty.
     
  6. iterator(): Returns an iterator across the queue's elements.
     
  7. offer(): inserts the specified element at the end of the queue.
     
  8. remove(): removes the specified element from the queue if it is present.
     
  9. removeAll(): Removes all of the queue's elements that are present in the provided collection.
     
  10. removeIf(): Removes all elements from this queue that meet the specified predicate filter.
     
  11. retainAll(): Only keep the elements in the queue that are in the provided collection.
     
  12. size(): returns the number of elements present in the queue.
     
  13. spilterator(): This function returns a spliterator over the entries in this queue.
     
  14. toarray(): Returns an array containing all of the queue's entries that are in the correct order.

Basic Operations

Addition of Elements

The ConcurrentLinkedQueue class provides add() and addAll() methods to add elements.

Below is the Java Program to Demonstrate addition of elements to ConcurrentLinkedQueue

Example

import java.util.concurrent.*;
import java.util.*;


public class ConcurrentLinkedQueueDemo {


    public static void main(String[] args)
    {


        // Create an instance of ConcurrentLinkedQueue
        ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();


        // Add String to queue using add method
        queue.add("city1");
        queue.add("city2");
        queue.add("city3");
        queue.add("city4");


        // Displaying the existing ConcurrentLinkedQueue
        System.out.println("ConcurrentLinkedQueue after add operations: " + queue);


        // create an ArrayList of Strings
        ArrayList<String> arraylist = new ArrayList<String>();


        // add String to ArrayList
        arraylist.add("person1");
        arraylist.add("person2");
        arraylist.add("person3");
        arraylist.add("person4");
        arraylist.add("person5");


        // Displaying the existing Collection
        System.out.println("Collection to be added: " + arraylist);


        // apply addAll() method and passed
        // the arraylist as parameter
        boolean response = queue.addAll(arraylist);


        // Displaying the existing ConcurrentLinkedQueue
        System.out.println("Collection added: " + response);


        // Displaying the existing ConcurrentLinkedQueue
        System.out.println("ConcurrentLinkedQueue after addAll opertaion: " + queue);
    }
}

Output

ConcurrentLinkedQueue after add operations: [city1, city2, city3, city4]
Collection to be added: [person1, person2, person3, person4, person5]
Collection added: true
ConcurrentLinkedQueue after addAll opertaion: [city1, city2, city3, city4, person1, person2, person3, person4, person5]


Try it on java online compiler.

Accessing the Elements

ConcurrentLinkedQueue's elements are accessed via Queue's peek() and element() methods.

The only difference between the element() and peek() is that element() throws an exception if the queue is empty.

Below is the Java Program to Demonstrate accessing elements of ConcurrentLinkedQueue.

Example

import java.util.*;
import java.util.concurrent.*;


public class ConcurrentLinkedQueueDemo {


    public static void main(String[] args) throws IllegalStateException
    {
        // Create an instance of ConcurrentLinkedQueue
        ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();


        // Add numbers to end of Queue
        queue.add(12345678);
        queue.add(78945612);
        queue.add(1223456);
        queue.add(98445126);


        // print queue
        System.out.println("Queue: " + queue);


        // print head
        System.out.println("Queue's head: " + queue.element());


        // print head
        System.out.println("Queue's head: " + queue.peek());
    }
}

Output

Queue: [12345678, 78945612, 1223456, 98445126]
Queue's head: 12345678
Queue's head: 12345678

Removing Elements

If a single instance of the provided element is present, the remove(Object o) function of ConcurrentLinkedQueue is used to delete it. It eliminates the element e, resulting in o.equals (e). If this ConcurrentLinkedQueue held the supplied element, it returns true; otherwise, it returns false.

Example

import java.util.concurrent.*;


public class ConcurrentLinkedQueueDemo {


    public static void main(String[] args)
    {


        // Create an instance of ConcurrentLinkedQueue
        ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();


        // Add Numbers to queue using add(e) method
        queue.add(1234);
        queue.add(5987);
        queue.add(77889);
        queue.add(9512);


        // Displaying the existing ConcurrentLinkedQueue
        System.out.println("ConcurrentLinkedQueue: " + queue);


        // apply remove() for Number 77889
        boolean response = queue.remove(77889);


        // print results
        System.out.println("Removed Number 77889 successfully: " + response);


        // Displaying the existing ConcurrentLinkedQueue
        System.out.println("Updated ConcurrentLinkedQueue: " + queue);
    }
}

Output

ConcurrentLinkedQueue: [1234, 5987, 77889, 9512]
Removed Number 77889 successfully: true
Updated ConcurrentLinkedQueue: [1234, 5987, 9512]

Iterating through the ConcurrentLinkedQueue

ConcurrentLinkedQueue's iterator() function returns an iterator with the same elements as this ConcurrentLinkedQueue in a suitable order. The components provided by this function are ordered from first(head) to last (tail). The iterator that is returned is inconsistent.

Below is the Java Program to Demonstrate Iteration over ConcurrentLinkedQueue.

Example

import java.util.concurrent.*;
import java.util.*;


public class ConcurrentLinkedQueueDemo {


    public static void main(String[] args)
    {
        // Create an instance of ConcurrentLinkedQueue
        ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();


        // Add String to queue using add(e) method
        queue.add("person1");
        queue.add("person2");
        queue.add("person3");
        queue.add("person4");


        // Displaying the existing ConcurrentLinkedQueue
        System.out.println("ConcurrentLinkedQueue : " + queue);


        // Call iterator() method
        Iterator iterator = queue.iterator();


        // Print elements of iterator
        System.out.println("\nThe String Values of iterator are:");
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Output

ConcurrentLinkedQueue : [person1, person2, person3, person4]

The String Values of iterator are:
person1
person2
person3
person4


Also read, Duck Number in Java And Hashcode Method in Java

Frequently Asked Questions

  1. Is ConcurrentLinkedQueue blocked?
    A ConcurrentLinkedQueue, unlike a LinkedBlockingQueue, is a non-blocking queue. As a result, once the queue is empty, it does not block a thread. Instead, null is returned. It'll throw a java since it's unbounded.
     
  2. How is Concurrentlinkedqueue thread-safe?
    You can synchronize atomic operations on concurrent collections. In other words, without any effort on your side, each individual call to the queue is assured to be thread-safe.
     
  3. What is a ConcurrentLinkedQueue?
    ConcurrentLinkedQueue is a thread-safe, unbounded queue that organizes elements in a FIFO order. New elements are added at the end of the queue, and items are added from the beginning. The ConcurrentLinkedQueue class and its iterator implement all of the Queue and Iterator interfaces' optional methods.

Conclusions

In this article, we have extensively discussed the ConcurrentLinkedQueue class in java. We learned about the constructors and methods of the ConcurrentLinkedQueue class.

In the end, we saw several basic operations that can be performed using various methods of ConcurrentLinkedQueue class with the help of examples.

We hope that this blog has helped you enhance your knowledge of the ArrayDeque class in java and if you would like to learn more about java, check out our articles, Circular Queue implementation and operationsAdvantages of Circular QueueApplications of Priority Queue and Java Archives. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass