Understanding Java's ConcurrentLinkedQueue: Implementation, Principles, and Usage

This article explains the thread‑safe ConcurrentLinkedQueue in Java, covering its lock‑free linked‑list structure, core methods such as add, offer, and poll, detailed source‑code analysis, and a multithreaded example demonstrating its behavior in high‑concurrency scenarios.

Big Data Technology & Architecture
Big Data Technology & Architecture
Big Data Technology & Architecture
Understanding Java's ConcurrentLinkedQueue: Implementation, Principles, and Usage

ConcurrentLinkedQueue is a thread‑safe, lock‑free, unbounded FIFO queue designed for high‑concurrency scenarios in Java.

It is implemented as a linked list with volatile head and tail references; each node contains a volatile item and a volatile next pointer. The queue relies on CAS (compare‑and‑swap) operations provided by sun.misc.Unsafe to achieve non‑blocking updates.

Key methods include constructors, add / offer, poll, and utility functions such as contains, isEmpty, and array conversion methods. The full method signatures are listed below.

// Constructors
public ConcurrentLinkedQueue()
public ConcurrentLinkedQueue(Collection<? extends E> c)

// Core operations
public boolean add(E e) { return offer(e); }
public boolean offer(E e) { /* implementation */ }
public E poll() { /* implementation */ }

// Utility methods
public boolean contains(Object o)
public boolean isEmpty()
public Iterator<E> iterator()
public int size()
public Object[] toArray()
public <T> T[] toArray(T[] a)

The offer(E e) method creates a new node and attempts to link it at the tail using a CAS loop that handles three cases: (1) the next pointer of the current tail is null, (2) the tail has moved forward, and (3) other concurrent modifications require retrying.

The poll() method removes the head node by atomically nulling its item field and updating the head reference. It also handles four cases to ensure correct progress under contention.

Both updateHead and lazySetNext use unsafe ordered writes to finalize pointer updates, with casHead and casNext providing the necessary atomicity.

Example

A demonstration program creates a shared ConcurrentLinkedQueue<String> and starts two threads that repeatedly add elements and iterate over the queue. The output shows interleaved insertions from both threads, illustrating the queue's thread‑safety. Replacing the queue with a non‑concurrent LinkedList would cause a ConcurrentModificationException.

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

/*
 * ConcurrentLinkedQueue is thread‑safe, while LinkedList is not.
 * This demo runs two threads that add to and iterate over the queue.
 */
public class ConcurrentLinkedQueueDemo1 {
    private static Queue<String> queue = new ConcurrentLinkedQueue<>();

    public static void main(String[] args) {
        new MyThread("ta").start();
        new MyThread("tb").start();
    }

    private static void printAll() {
        for (String value : queue) {
            System.out.print(value + ", ");
        }
        System.out.println();
    }

    private static class MyThread extends Thread {
        MyThread(String name) { super(name); }
        @Override
        public void run() {
            for (int i = 0; i < 6; i++) {
                String val = Thread.currentThread().getName() + i;
                queue.add(val);
                printAll();
            }
        }
    }
}

The sample output demonstrates that the queue correctly handles concurrent additions without throwing exceptions.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaconcurrencymultithreadingData Structurelock‑freeConcurrentLinkedQueue
Big Data Technology & Architecture
Written by

Big Data Technology & Architecture

Wang Zhiwu, a big data expert, dedicated to sharing big data technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.