ConcurrentLinkedDeque Drains From Both Ends

addFirst and pollLast drain a ConcurrentLinkedDeque from opposite ends without coordination; size() walks the chain and iterators stay weakly consistent.

JavaData Integrity

Code

snippet
import java.util.concurrent.ConcurrentLinkedDeque;

public class TwoEndedQueue {

    public static void main(String[] args) {
        ConcurrentLinkedDeque<String> jobs = new ConcurrentLinkedDeque<>();

        // 生产端从一头压入,消费端从另一头取走:两端线程无需协调
        jobs.addFirst("render-footer");
        jobs.addFirst("render-header");
        jobs.addFirst("resize-banner");
        System.out.println("first: " + jobs.peekFirst());
        System.out.println("last: " + jobs.peekLast());

        // pollLast 取不到时返回 null,而不是抛异常
        System.out.println("take: " + jobs.pollLast());
        System.out.println("take: " + jobs.pollLast());

        // size() 不是常数时间:要遍历整条链,并发场景别靠它做判断
        System.out.println("size walks the chain: " + jobs.size());

        // descendingIterator 从尾部走向头部,弱一致:遍历中允许并发增删
        jobs.descendingIterator().forEachRemaining(j -> System.out.println("desc: " + j));

        System.out.println("drained: " + jobs.pollLast());
        System.out.println("empty poll: " + jobs.pollLast());

        // 与多数并发集合一样不接受 null 元素
        try {
            jobs.addFirst(null);
        } catch (NullPointerException e) {
            System.out.println("null rejected");
        }
    }
}

How it works

ConcurrentLinkedDeque Drains From Both Ends comes down to the class TwoEndedQueue and the function main.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

The signature doing the primary work is public static void main(String[] args)

Look for the first:, last:, take: prefixes once the file starts running; each one ties a printed line to the step that produced it.

Key statements worth quoting

ConcurrentLinkedDeque<String> jobs = new ConcurrentLinkedDeque<>();
jobs.addFirst("render-footer");
jobs.addFirst("render-header");

Interactive Tools for This Topic

FAQ

What does ConcurrentLinkedDeque Drains From Both Ends print when run?
Invoke the file as-is — the `first:`, `last:`, `take:` prefixes identify which step printed each line.