June 28, 2022

ConcurrentLinkedQueue in Java With Examples

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. ConcurrentLinkedQueue class implements Queue interface and is part of java.util.concurrent package.

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

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

public class ConcurrentLQ {
  public static void main(String[] args) {
    Queue<Integer> conQueue = new ConcurrentLinkedQueue<>();
    conQueue.add(5);
    conQueue.add(null);
  }
}
Output
Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:221)
	at java.base/java.util.concurrent.ConcurrentLinkedQueue.offer(ConcurrentLinkedQueue.java:355)
	at java.base/java.util.concurrent.ConcurrentLinkedQueue.add(ConcurrentLinkedQueue.java:283)
	at com.knpcode.programs.ConcurrentLQ.main(ConcurrentLQ.java:11)

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.

public class ConcurrentLQ {
  public static void main(String[] args) {
    ExecutorService executor = Executors.newFixedThreadPool(4);
    Queue<Integer> conQueue = new ConcurrentLinkedQueue<>();
    // One Producer thread
    executor.execute(new ConProducer(conQueue));
    // Two Consumer thread
    executor.execute(new ConConsumer(conQueue));
    executor.execute(new ConConsumer(conQueue));	
    executor.shutdown();
  }
}

//Producer
class ConProducer implements Runnable{
  Queue<Integer> conQueue;
  ConProducer(Queue<Integer> conQueue){
    this.conQueue = conQueue;
  }
  @Override
  public void run() {
    for(int i = 0; i < 6; i++){
      System.out.println("Adding to queue-" + i);
      conQueue.add(i);	
    }
  }
}
//Consumer
class ConConsumer implements Runnable{
  Queue<Integer> conQueue;
  ConConsumer(Queue<Integer> conQueue){
    this.conQueue = conQueue;
  }
  @Override
  public void run() {		
    for(int i = 0; i < 3; i++){
      try {
        TimeUnit.MILLISECONDS.sleep(50);			
        System.out.println("Thread Name -" + Thread.currentThread().getName() + " Consumer retrieved- " + conQueue.poll());
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
}
Output
Adding to queue-0
Adding to queue-1
Adding to queue-2
Adding to queue-3
Adding to queue-4
Adding to queue-5
Thread Name -pool-1-thread-2 Consumer retrieved- 0
Thread Name -pool-1-thread-3 Consumer retrieved- 1
Thread Name -pool-1-thread-3 Consumer retrieved- 3
Thread Name -pool-1-thread-2 Consumer retrieved- 2
Thread Name -pool-1-thread-3 Consumer retrieved- 4
Thread Name -pool-1-thread-2 Consumer retrieved- 5

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


You may also like

No comments:

Post a Comment