Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

ConcurrentLinkedQueue in Java With Examples

Last Updated on March 11, 2022 by Ria Pathak

Class Declaration

public class ConcurrentLinkedQueue
extends AbstractQueue
implements Queue, Serializable

Here, E is the data type of the elements which will be stored in the queue.

ConcurrentLinkedQueue class in java extends AbstractQueue interface and implements Queue interface. This class was added in Java 5. This class is a member of the Java collections framework.

ConcurrentLinkedQueue class is a thread-safe queue which is unbounded. It is based on linked nodes.

  • This queue follows the FIFO principle.
  • This queue orders elements in FIFO (first-in-first-out) order.
  • To understand it better, you can take the example of people standing in the queue in front of the bank. The person who joined the queue first will have had its work done first.

  • The head of the queue is determined by checking the time each node has been on the queue.

    • The element of the queue which is being contained for the maximum time is the head.
    • The head is always on the top of the queue.
    • This class provides two methods to access the head element, peek() and poll().
  • Like the head, the tail of the queue is also determined by checking the time each node has been on the queue.

    • The element of the queue which is being contained for the minimum time is the tail.
    • New elements are inserted at the tail of the queue using add() or addAll().
    • Currently, this class does not provide any method for accessing the tail directly.
    • The tail is always at the bottom of the queue.
  • The ConcurrentLinkedQueue is mostly used when many threads have to share access to common collections like ArrayList, Stack, PriorityQueue, etc.

    • The ConcurrentLinkedQueue class is the most appropriate choice in such cases because, unlike other concurrent collection implementations; this class does not permit the use of null elements.
    • The implementation of ConcurrentLinkedQueue is based on an efficient "wait-free" algorithm.
  • The ConcurrentLinkedQueue iterators can be used to traverse the elements of the queue.

    • Iterators are weakly consistent and are used for returning elements.
    • The iterators may proceed concurrently with other operations and do not throw ConcurrentModificationException.
  • The reason behind the inaccurate results are that some methods of this class like addAll, containsAll and toArray when called are not guaranteed to be performed atomically.

Constructors

Constructor Description
Concurrentlinkedqueue() This constructor is used to create an empty Concurrentlinkedqueue.
Concurrentlinkedqueue(Collection c) This constructor is used to create a Concurrentlinkedqueue initially containing the elements of the specified elements.

Methods

Method Description
add(E e) This method is used to add a specified element at the tail of this queue. It returns true, if the specified element was successfully added, false otherwise.
addAll(Collection c) This method is used to add all the elements in the specified collection to the end of this queue in the same order as returned by the collection’s iterator. It returns true if the specified collection was successfully added, false otherwise.
contains(Object o) This method is used to check whether the specified element is present in this queue or not. It returns true if the element is contained in the queue, false otherwise.
isEmpty() This method is used to check whether this queue is empty or not. It returns true if this queue is empty, false otherwise.
iterator() This method returns an iterator over the elements of this queue.
offer(E e) This method is used to add a specified element at the tail of this queue. It returns true, if the specified element was successfully added, false otherwise.
peek() This method is used to retrieve the head of the queue. If this queue is empty, then it returns null.
poll() This method is used to remove the head of the queue. If this queue is empty, then it returns null.
remove(Object o) This method is used to remove this specified element from the queue. It returns false if this queue is empty.
size() This method returns the size of this queue.
toArray() This method returns an object array containing all the elements of this queue in proper order.
toArray(T[] a) This method returns an array of the specified type, containing all the elements of this queue in proper order.

Examples

Example 1:

In this example, we will see how to create a ConcurrentLinkedQueue using different constructors and add elements to them.

Code Implementation
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Prepbytes {

    public static void main(String[] args) {

        /*
         * Create an empty ConcurrentLinkedQueue
         */
        ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();

        // Print this queue
        System.out.println("Empty ConcurrentLinkedQueue: " + queue);

        // Add values to this queue
        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(4);

        // Print this queue
        System.out.println("ConcurrentLinkedQueue: " + queue);

        // Create a collection
        ArrayList c = new ArrayList();

        // Add values to the collection
        c.add(5);
        c.add(6);
        c.add(7);

        // Add the collection to this queue using addAll()
        queue.addAll(c);

        // Print modified queue
        System.out.println("ConcurrentLinkedQueue: " + queue);

        /*
         * Create a ConcurrentLinkedQueue containing elements of a specified collection
         */
        ConcurrentLinkedQueue queueC = new ConcurrentLinkedQueue(c);

        // Print this queue
        System.out.println("ConcurrentLinkedQueue initialized with specified elements: " + queueC);
    }
}
Output

Empty ConcurrentLinkedQueue: []
ConcurrentLinkedQueue: [1, 2, 3, 4]
ConcurrentLinkedQueue: [1, 2, 3, 4, 5, 6, 7]
ConcurrentLinkedQueue initialized with specifed elements: [5, 6, 7]

Example 2

In this example, we will see:

  • How to retrieve, remove the head of this queue.
  • How to check whether a specified element is present in the queue or not
  • How to remove a specified element from the queue.
Code Implementation
import java.util.concurrent.ConcurrentLinkedQueue;

public class Prepbytes {

    public static void main(String[] args) {

        /*
         * Create an empty ConcurrentLinkedQueue
         */
        ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();

        // Add values to this queue
        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(4);
        queue.add(9);
        queue.add(11);

        // Print this queue
        System.out.println("ConcurrentLinkedQueue: " + queue);

        System.out.println("Head of the the queue before poll() operation: " + queue.peek());
        
        queue.poll();
        
        System.out.println("Head of the the queue after poll() operation: " + queue.peek());
        
        System.out.println("Do queue contains 9: " + queue.contains(9));
        
        queue.remove(9);
        
        System.out.println("Do queue contains 9 after remove() operation: " + queue.contains(9));
    }
}

Output

ConcurrentLinkedQueue: [1, 2, 3, 4, 9, 11]
Head of the the queue before poll() operation: 1
Head of the the queue after poll() operation: 2
Do queue contains 9: true
Do queue contains 9 after remove() operation: false

Example 3

In this example, we will see how to iterate through the elements of this queue.

Code Implementation
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Prepbytes {
    public static void main(String[] args) {

        /*
         * Create an empty ConcurrentLinkedQueue
         */
        ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();

        // Add values to this queue
        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(4);
        queue.add(9);
        queue.add(11);

    // Create a integer iterator of this queue using iterator() method
        Iterator iterator = queue.iterator();
    
    // Print the values of the iterator.
        System.out.println("The values of iterator are:");

    // Traversing the iterator
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
   }
}
Output

The values of iterator are:
1
2
3
4
9
11

Example 4

In this example, we will see the working of the toArray() method.

Code Implementation
import java.util.concurrent.ConcurrentLinkedQueue;

public class Prepbytes {

    public static void main(String[] args) {

        /*
         * Create an empty ConcurrentLinkedQueue
         */
        ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();

        // Add values to this queue
        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(4);
        queue.add(9);
        queue.add(11);

    // Create a object array from the queue
        Object[] arr = (Object[]) queue.toArray();
       
    // Print elements of the queue
        for(Object o : arr) {
            System.out.println(o);
        }
   }
}
Output

1
2
3
4
9
11

So, in this blog we have tried to explain the ConcurrentLinkedQueue in Java with examples. Java Collection Framework is very important when it comes to coding interviews. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List.

Leave a Reply

Your email address will not be published. Required fields are marked *