ConcurrentLinkedQueue Non-Blocking Handoff

Hand tasks between threads with a lock-free ConcurrentLinkedQueue: offer never blocks, poll returns null when drained, and size() is only an O(n) estimate.

JavaResilience

Code

snippet
import java.util.concurrent.ConcurrentLinkedQueue;

public class JobHandoff {

    public static void main(String[] args) throws InterruptedException {
        // 无锁(lock-free)handoff 队列:offer 永不阻塞,也没有容量上限
        ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();

        Thread producer = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                queue.offer("task-" + i);
            }
        });
        producer.start();
        producer.join(); // join 之后主线程才能安全消费全部任务

        // poll 取走队首;取不到时返回 null 而不是挂起当前线程
        System.out.println("polled: " + queue.poll());
        System.out.println("rest:   " + queue);

        // size() 要遍历整条链表且是弱一致估计:并发判空一律用 isEmpty()
        System.out.println("empty: " + queue.isEmpty() + " size: " + queue.size());
    }
}

Inside the snippet

Count the class JobHandoff as the entire surface area of ConcurrentLinkedQueue Non-Blocking Handoff.

Iteration happens inside for (int i = 0; i < 3; i++) — everything outside it runs once.

Putting it to use

Running the file prints labeled results such as polled:, rest:, empty: — each operation’s effect is visible in the output.

Core lines

Thread producer = new Thread(() -> {
for (int i = 0; i < 3; i++) {
queue.offer("task-" + i);
}
});

Interactive Tools for This Topic

FAQ

What does ConcurrentLinkedQueue Non-Blocking Handoff print when run?
Run it as a complete program — the output lines carry labels such as `polled:`, `rest:`, `empty:`.