ConcurrentLinkedQueue in Java

ConcurrentLinkedQueue in Java implements Queue interface and is part of java.util.concurrent package.

ConcurrentLinkedQueue in Java is an unbounded queue which is thread-safe. It stores its elements as linked nodes where each node stores a reference to the next node.

How ConcurrentLinkedQueue differs from the BlockingQueue implementations like ArrayBlockingQueue, PriorityBlockingQueue is that ConcurrentLinkedQueue is non-blocking so the operations in this queue don’t block. Since ConcurrentLinkedQueue is non-blocking there are no put() or take() methods which will block if required.

This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue.

ConcurrentLinkedQueue doesn’t allow null elements

Like most other concurrent collection implementations, this class does not permit the use of null elements.

Output

As you can see trying to add null to the queue results in NullPointerException.

Java ConcurrentLinkedQueue constructors

  • ConcurrentLinkedQueue()– Creates a ConcurrentLinkedQueue that is initially empty.
  • ConcurrentLinkedQueue(Collection<? extends E> c)– Creates a ConcurrentLinkedQueue initially containing the elements of the given collection, added in traversal order of the collection’s iterator.

ConcurrentLinkedQueue Java example

Here is an example of producer-consumer in Java using ConcurrentLinkedQueue. There is one producer thread and two consumers thread.

Output

That’s all for the topic ConcurrentLinkedQueue in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.