Java Materials
← Core Java

Concurrent collections

Follow array snapshots, hash bins, skip-list indexes, queue nodes and thread handoffs. Each lesson explains the Java API contract and identifies OpenJDK 21 implementation details that may change in later releases.

Choose a collection

Decide whether you need key lookup, ordering, a bounded backlog, direct handoff or a snapshot. A thread-safe collection protects its own operations. Application invariants that span multiple actions still need coordination.

Run from core-java-lab with JDK 21
java ConcurrentCollectionsLab.java
CollectionUse it when you need
CopyOnWriteArrayListRead-mostly lists; stable snapshot iteration
CopyOnWriteArraySetSmall, read-mostly unique memberships
ConcurrentSkipListSetConcurrent sorted membership and ranges
ConcurrentHashMapConcurrent hash access and atomic per-key updates
ConcurrentSkipListMapOrdered keys, ranges and nearest-key lookups
ConcurrentHashMap.newKeySet()Concurrent hash membership and atomic claims
ConcurrentLinkedQueueUnbounded nonblocking FIFO
ConcurrentLinkedDequeUnbounded nonblocking access at both ends
ArrayBlockingQueueBounded FIFO with preallocated storage
LinkedBlockingQueueLinked FIFO with optional capacity and separate endpoint locks
PriorityBlockingQueueUnbounded blocking consumer queue ordered by priority
DelayQueueAvailability gated by expiry
SynchronousQueueZero-capacity rendezvous
LinkedTransferQueueBuffered enqueue plus receipt coordination
LinkedBlockingDequeBlocking access at both ends with optional capacity

CopyOnWriteArrayList

Definition:

A thread-safe list that publishes a replacement backing array for structural changes.

Explanation:

A listener registry dispatches one event while another thread changes the subscribers. The dispatch should complete against a stable membership list. CopyOnWriteArrayList makes that snapshot cheap to obtain and shifts the cost to writes.

Illustration image:

A snapshot iterator keeps the previous array. Successful mutations publish another array; both arrays hold references to the existing elements. Array snapshots across a writeCaptured iteratoremail0sms1Current array refsms0push1Reader retains old arrayWriter publishes copy
A snapshot iterator keeps the previous array. Successful mutations publish another array; both arrays hold references to the existing elements.

Example:

Java · runnable lab excerpt
static void copyOnWriteArrayList() {
    var listeners = new CopyOnWriteArrayList<>(List.of("email", "sms"));
    Iterator<String> snapshot = listeners.iterator();
    listeners.remove("email");
    listeners.add("push");
    var observed = new ArrayList<String>();
    snapshot.forEachRemaining(observed::add);
    check(observed.equals(List.of("email", "sms")));
    check(listeners.equals(List.of("sms", "push")));
}

Expected result. The snapshot returns [email, sms]. A fresh list read returns [sms, push].

Internal working:

Inside OpenJDK

The list holds a volatile reference to its current backing array. Structural writes serialize under a lock, prepare a replacement array and publish it. Iterators capture the current array reference when constructed. The writer never edits the captured array in place, so the iterator can read it without holding the writer lock.

Trace the example

Create the iterator when the array holds email and sms. Remove email and add push; subsequent readers see sms and push. The old iterator still reads email and sms. Objects are shared: copying the array does not clone mutable listeners.

Cost and limits

Indexed access is constant time. Appending, inserting or removing usually copies O(n) references, and long-lived iterators can keep old arrays alive. Iterator mutation methods are unsupported. Choose this for small read-mostly lists; for frequent changes, measure copy and allocation rates.

Interview questions:

What does an iterator see after someone adds an element?

It continues to traverse the original array snapshot; a new iterator sees the published replacement.

CopyOnWriteArraySet

Definition:

A small concurrent set backed by a copy-on-write array.

Explanation:

Use this for a small subscription set when readers iterate much more often than writers change membership. The example ignores a duplicate registration and then shows that an earlier iterator does not see a new subscriber.

Illustration image:

A snapshot iterator keeps the previous array. Successful mutations publish another array; both arrays hold references to the existing elements. Array snapshots across a writeCaptured iteratoremail0sms1Current array refemail0sms1push2Reader retains old arrayWriter publishes copyadd(email) makes no copy
A snapshot iterator keeps the previous array. Successful mutations publish another array; both arrays hold references to the existing elements.

Example:

Java · runnable lab excerpt
static void copyOnWriteArraySet() {
    var subscribers = new CopyOnWriteArraySet<>(List.of("email", "sms"));
    var snapshot = subscribers.iterator();
    check(!subscribers.add("email"));
    check(subscribers.add("push"));
    check(snapshot.next().equals("email"));
    check(snapshot.next().equals("sms") && !snapshot.hasNext());
    check(subscribers.size() == 3);
}

Expected result. Adding email returns false, adding push returns true, and the snapshot contains only email and sms.

Internal working:

Inside OpenJDK

The set delegates to a CopyOnWriteArrayList. Insertion searches by equals, and addIfAbsent rechecks when another write might have invalidated its initial view. A successful addition publishes a copied array. There is no hash bucket lookup, so membership checks are linear.

Trace the example

The original array is email and sms. Inserting email again returns false and leaves membership unchanged. Adding push returns true and publishes a new array. The old iterator stays on its original array.

Cost and limits

Reads avoid acquisition of the mutation lock for ordinary traversal, but each successful insertion can allocate and copy O(n). Use a hash-based concurrent key set for larger sets or frequently updated membership; choose a skip-list-backed set for sorted navigation.

Interview questions:

Does adding an existing element copy the array?

The duplicate is rejected; only a successful membership change requires a new snapshot.

ConcurrentSkipListSet

Definition:

A concurrent sorted set backed by skip-list indexing.

Explanation:

Use this when concurrent membership needs sorted traversal or range queries. For example, a scheduler can ask for the first eligible deadline at or after a cutoff without sorting a copy of the whole set.

Illustration image:

Illustrative search for 40: skip along upper levels, then descend before overshooting. Base nodes remain in key order. Index levels vary with the data and insertion choices. Search path through sparse index levelsIndex L2Index L1Base datahead50head30501030405070Drop before 5040 at base level
Illustrative search for 40: skip along upper levels, then descend before overshooting. Base nodes remain in key order. Index levels vary with the data and insertion choices.

Example:

Java · runnable lab excerpt
static void concurrentSkipListSet() {
    var ranges = new ConcurrentSkipListSet<Integer>(List.of(10, 30, 50, 70));
    NavigableSet<Integer> view = ranges.subSet(20, true, 60, false);
    ranges.add(40);
    check(ranges.ceiling(31) == 40);
    check(new ArrayList<>(view).equals(List.of(30, 40, 50)));
}

Expected result. The nearest eligible key is 40. The range view contains [30, 40, 50].

Internal working:

Inside OpenJDK

The set uses a ConcurrentNavigableMap backed by a ConcurrentSkipListMap. Ordered data nodes live at the bottom. Sparse probabilistic index layers route searches past runs of nodes. Ordering determines equivalence through the comparator or natural order; two different objects comparing as zero occupy one position.

Trace the example

A range view from 20 inclusive to 60 exclusive is taken before 40 is inserted. The view stays backed by the set, so later traversal includes 30, 40 and 50. ceiling(31) returns 40. Iterators have weak consistency, so traversal concurrent with mutation is not a frozen range.

Cost and limits

Basic searches, inserts and removals have expected logarithmic cost. Avoid computing size as a coordination check and expect ascending traversal to be more efficient than descending traversal in the JDK skip-list implementation.

Interview questions:

Is subSet a frozen copy?

No. It is a backed range view whose iterators can observe some concurrent changes.

ConcurrentHashMap

Definition:

A concurrent hash table offering thread-safe access and atomic per-key operations.

Explanation:

ConcurrentHashMap supports shared lookups and independent-key updates. In the example two workers merge increments into the same key, which would lose increments with a separate get and put.

Illustration image:

Different keys can select the same bin. ConcurrentHashMap checks hash and equality inside the bin. The key-set view uses a shared TRUE value for membership. Hash spread → indexed bin → equalitypenspread hash∅0bin 11bin 22∅3pen = 2,000collisionCAS when bin is emptyCheck equality inside bin
Different keys can select the same bin. ConcurrentHashMap checks hash and equality inside the bin. The key-set view uses a shared TRUE value for membership.

Example:

Java · runnable lab excerpt
static void concurrentHashMap() throws Exception {
    ConcurrentMap<String, Integer> counts = new ConcurrentHashMap<>();
    var ready = new CountDownLatch(1);
    try (var workers = Executors.newVirtualThreadPerTaskExecutor()) {
        Callable<Void> count = () -> {
            ready.await();
            for (int i = 0; i < 1000; i++) counts.merge("pen", 1, Integer::sum);
            return null;
        };
        var first = workers.submit(count);
        var second = workers.submit(count);
        ready.countDown();
        first.get(2, TimeUnit.SECONDS);
        second.get(2, TimeUnit.SECONDS);
    }
    check(counts.get("pen") == 2000);
    check(counts.replace("pen", 2000, 0));
    check(!counts.remove("pen", 2000));
}

Expected result. The final count is 2000; the conditional replacement succeeds, and the stale conditional removal fails.

Internal working:

Inside OpenJDK 21

A spread hash selects a table bin. A vacant bin can be initialized with CAS. Many contended updates to a populated list bin synchronize on the bin's first node and recheck the bin. Eligible collisions may become tree bins; if the table is too small the implementation can resize instead. During migration a forwarded bin points readers and writers toward the next table, and multiple threads can assist transfer.

Atomicity and visibility

A successful per-key update happens-before a non-null retrieval that reports that value. merge, compute and conditional updates are useful for one-key invariants. A mapped ArrayList remains mutable shared state. Do not perform slow I/O or recursively update this map from a remapping function. A two-account transfer belongs in a wider coordination boundary.

Trace the example

Two workers each apply 1,000 merge operations. After joining both futures there are 2,000 counts. The conditional replace resets only the observed value, and a stale conditional remove fails. Traversal during updates is weakly consistent; null keys and values are rejected.

Cost and limits

Hash lookup is expected constant time with good distribution. Hot keys serialize their updates even in a concurrent map. For frequency metrics under contention, consider LongAdder and read its exact aggregate only after writers stop if an exact final total is needed.

Interview questions:

Can two compute calls safely enforce a transfer between keys?

Per-key atomicity does not cover the two-key invariant. Use wider coordination or a database transaction.

ConcurrentSkipListMap

Definition:

A concurrent navigable map whose keys are kept in sorted order.

Explanation:

Choose a concurrent sorted map for time windows, a price ladder or other nearest-key lookups. Unlike a hash map, the ordering structure is part of the normal read path.

Illustration image:

Illustrative search for 40: skip along upper levels, then descend before overshooting. Base nodes remain in key order. Index levels vary with the data and insertion choices. Search path through sparse index levelsIndex L2Index L1Base datahead50head30501030405070Drop before 5040 at base level
Illustrative search for 40: skip along upper levels, then descend before overshooting. Base nodes remain in key order. Index levels vary with the data and insertion choices.

Example:

Java · runnable lab excerpt
static void concurrentSkipListMap() {
    ConcurrentNavigableMap<Integer, String> prices = new ConcurrentSkipListMap<>();
    prices.put(10, "bronze");
    prices.put(30, "silver");
    prices.put(50, "gold");
    var window = prices.subMap(10, true, 50, false);
    prices.put(20, "promo");
    check(prices.floorEntry(27).getValue().equals("promo"));
    check(new ArrayList<>(window.keySet()).equals(List.of(10, 20, 30)));
}

Expected result. floorEntry(27) returns 20=promo; the half-open [10, 50) view contains keys [10, 20, 30].

Internal working:

Inside OpenJDK 21

The base layer stores data nodes in key order. Randomized upper index levels contain shortcuts to selected base nodes. Search walks right while keys remain below the target, then drops a level. Insertions and removals coordinate using CAS and retries; logical deletion and cleanup let searches bypass obsolete nodes. The diagram shows representative index levels, not a guaranteed layout.

Trace the example

floorEntry(27) locates the greatest key no greater than 27. Inserting 20 changes the result to promo. subMap makes a backed sorted view: keys inserted inside its bounds become visible, while writes through the view outside bounds are rejected.

Cost and limits

Basic operations have expected O(log n) cost. Snapshot entries returned by navigation do not give atomic transactions. A set or map range is a live view, and iteration over it is weakly consistent.

Interview questions:

Why use this instead of ConcurrentHashMap for a price ladder?

It can find nearest keys and expose sorted range views without sorting a separate collection.

ConcurrentHashMap.newKeySet()

Definition:

A concurrent set view backed by ConcurrentHashMap.

Explanation:

Use newKeySet for hash-based membership across threads, such as one-process duplicate suppression. An atomic add result identifies the thread that installed a new key.

Illustration image:

Different keys can select the same bin. ConcurrentHashMap checks hash and equality inside the bin. The key-set view uses a shared TRUE value for membership. Hash spread → indexed bin → equalitypenspread hash∅0bin 11bin 22∅3pen = TRUEcollisionCAS when bin is emptyCheck equality inside bin
Different keys can select the same bin. ConcurrentHashMap checks hash and equality inside the bin. The key-set view uses a shared TRUE value for membership.

Example:

Java · runnable lab excerpt
static void concurrentKeySet() throws Exception {
    Set<String> seen = ConcurrentHashMap.newKeySet();
    var accepted = new AtomicInteger();
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        Runnable accept = () -> {
            if (seen.add("event-42")) accepted.incrementAndGet();
        };
        var first = executor.submit(accept);
        var second = executor.submit(accept);
        first.get(2, TimeUnit.SECONDS);
        second.get(2, TimeUnit.SECONDS);
    }
    check(accepted.get() == 1 && seen.contains("event-42"));
}

Expected result. Both workers finish, the set contains event-42 once and only one worker observed a successful claim.

Internal working:

Inside OpenJDK 21

The factory returns a KeySetView backed by ConcurrentHashMap with Boolean.TRUE as the mapped value. Set addition uses the map's conditional absent-key behavior. A plain map.keySet() view does not generally support add unless a mapped value is supplied through keySet(mappedValue).

Trace the example

Two workers attempt to add event-42. Exactly one add returns true, so only that worker increments the accepted count. Separate contains then add would not identify a unique winner. If processing fails after claiming the key, define when to remove or retain it.

Cost and limits

Membership is expected constant time with good hash distribution, iteration is weakly consistent, null keys are unsupported and there is no built-in expiry. Use durable idempotency for cross-instance or crash-safe deduplication.

Interview questions:

Why is add's return value better than contains followed by add for claiming an ID?

Only one add returns true for the first insertion; separate checking and writing can race.

ConcurrentLinkedQueue

Definition:

An unbounded nonblocking FIFO backed by linked nodes.

Explanation:

An unbounded nonblocking FIFO is a suitable handover when overload is managed separately. offer and poll do not wait for capacity or data. An empty read returns null.

Illustration image:

Next pointers link a FIFO chain. Endpoint pointers can lag the logical ends; traversal can skip logically removed nodes. Linked FIFO with concurrent endpointsFront / headBack / tailABCCAS links; logical removal clears the item
Next pointers link a FIFO chain. Endpoint pointers can lag the logical ends; traversal can skip logically removed nodes.

Example:

Java · runnable lab excerpt
static void concurrentLinkedQueue() {
    var events = new ConcurrentLinkedQueue<String>();
    check(events.offer("A") && events.offer("B"));
    check(events.peek().equals("A"));
    check(events.poll().equals("A") && events.poll().equals("B"));
    check(events.poll() == null);
}

Expected result. The polls produce A, B and then null. Peeking does not consume A.

Internal working:

Inside OpenJDK 21

A singly linked structure tracks head and tail references that can lag the logical endpoints. Appending links a new node with CAS; removing commonly CASes the node's item to null. Traversals skip logically removed nodes, and incidental cleanup advances links or endpoints. This is a nonblocking algorithm, not a wait-free guarantee for each caller.

Trace the example

Offer A, then B. peek observes A without claiming it; poll claims A, then B. A production consumer must never treat peek followed by a later poll as an atomic reservation because another consumer can win between the calls.

Cost and limits

Avoid size in hot-path admission policy; it traverses nodes and concurrent updates can make the count stale immediately. The queue has no inherent memory bound; use a bounded BlockingQueue or a separate admission mechanism when backlog must be capped.

Interview questions:

Why avoid frequent size checks in an admission loop?

size is traversal-based and its answer can be outdated immediately under concurrent mutation.

ConcurrentLinkedDeque

Definition:

An unbounded nonblocking deque with operations at both ends.

Explanation:

Use a shared nonblocking deque when tasks can be added or removed from either end. One example is placing urgent work at the front while ordinary work goes to the back.

Illustration image:

Two-way links support both ends. Endpoint pointers can lag the logical ends; traversal can skip logically removed nodes. Linked deque with concurrent endpointsFront / headBack / tailABCCAS links; logical removal clears the itemEither end can remove
Two-way links support both ends. Endpoint pointers can lag the logical ends; traversal can skip logically removed nodes.

Example:

Java · runnable lab excerpt
static void concurrentLinkedDeque() {
    var work = new ConcurrentLinkedDeque<String>();
    work.addLast("normal");
    work.addFirst("urgent");
    work.addLast("background");
    check(work.pollFirst().equals("urgent"));
    check(work.pollLast().equals("background"));
    check(work.pollFirst().equals("normal"));
}

Expected result. The example takes urgent from the front, background from the back and then normal.

Internal working:

Inside OpenJDK 21

Nodes carry predecessor and successor links. Head and tail pointers are approximate navigation anchors. Endpoint updates use CAS, and removals logically clear the item before nodes are physically unlinked. Traversals tolerate deleted nodes. These internals are more complex than a doubly linked list modified by one thread.

Trace the example

Insert normal at the back, urgent at the front and background at the back. Front poll returns urgent, back poll returns background and the remaining value is normal. Under concurrency a pair of endpoint operations does not create a transaction or global priority policy.

Cost and limits

Iteration is weakly consistent and size walks the structure. It is unbounded and has no blocking take operation. If readiness or bounded insertion must be signaled through the deque itself, use LinkedBlockingDeque.

Interview questions:

Does pollFirst wait for future work?

No. It returns null when no element is available. Use a blocking deque for interruptible waiting.

ArrayBlockingQueue

Definition:

A fixed-capacity blocking FIFO backed by a circular array.

Explanation:

Use a fixed-capacity FIFO for producer–consumer work when memory and backlog need a hard bound. Decide explicitly what should happen at capacity: reject, wait for a deadline or wait interruptibly.

Illustration image:

The put cursor wraps to slot 0 after A is removed. The take cursor is at slot 1, so the remaining FIFO order is B then C. Physical slots versus FIFO orderBefore take(A)A0B1count = 2After offer(C)C0B1count = 2Next take → B
The put cursor wraps to slot 0 after A is removed. The take cursor is at slot 1, so the remaining FIFO order is B then C.

Example:

Java · runnable lab excerpt
static void arrayBlockingQueue() throws InterruptedException {
    BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
    queue.put("A");
    queue.put("B");
    check(!queue.offer("C"));
    check(queue.take().equals("A"));
    check(queue.offer("C", 100, TimeUnit.MILLISECONDS));
    check(queue.take().equals("B") && queue.take().equals("C"));
}

Expected result. Offer C fails when full, then succeeds after A is taken. The remaining two dequeues return B, then C.

Internal working:

Inside OpenJDK 21

A fixed array and circular putIndex and takeIndex track slots. A single ReentrantLock protects both endpoints and the item count. notEmpty and notFull conditions coordinate consumers and producers. A take clears the slot, advances the index with wraparound and signals capacity. Optional fairness controls lock acquisition order and can trade throughput for more predictable waiting.

Trace the example

Capacity two holds A and B. Immediate offer(C) returns false. Removing A frees its slot, so an offer can store C at that same physical index after the write cursor wraps. FIFO is B then C even though the physical layout places C in slot zero.

Cost and limits

End operations are constant time excluding waiting. The array allocation is fixed and there is no linked-node allocation per item. All puts and takes contend on the same lock. Measure wait time and depth under bursts before setting capacity or enabling fairness.

Interview questions:

Why can the next item occupy a higher index than the newest item?

Take and put indices wrap independently; logical order follows the take cursor, not physical index order.

LinkedBlockingQueue

Definition:

An optionally bounded linked FIFO with blocking operations.

Explanation:

Use a bounded linked FIFO when the chosen capacity and workload benefit from separate put and take coordination. Supply a capacity explicitly when backlog is part of your resource budget.

Illustration image:

Next pointers link a FIFO chain. The configured capacity and condition signals control admission. Linked FIFO with bounded admissionFront / headBack / tailABCTake lock • atomic count • put lock
Next pointers link a FIFO chain. The configured capacity and condition signals control admission.

Example:

Java · runnable lab excerpt
static void linkedBlockingQueue() throws InterruptedException {
    BlockingQueue<String> queue = new LinkedBlockingQueue<>(2);
    queue.put("invoice-1");
    queue.put("invoice-2");
    check(queue.remainingCapacity() == 0 && !queue.offer("invoice-3"));
    check(queue.take().equals("invoice-1"));
    check(queue.offer("invoice-3"));
}

Expected result. The initial third offer fails. Invoice 1 is taken first, after which Invoice 3 can be added.

Internal working:

Inside OpenJDK 21

A dummy head and tail delimit a singly linked node chain. A put lock protects appends and a take lock protects removals. An AtomicInteger count bridges the locks, so ordinary producer and consumer operations can make progress at separate ends. Empty-to-nonempty and full-to-not-full transitions signal the opposite side; conditions support blocking and timed operations.

Trace the example

After two invoices the bounded queue rejects an immediate third offer. Removing the first invoice frees a slot. A later offer can add the third invoice at the tail. The dummy node is an implementation detail and is never returned as an invoice.

Cost and limits

End operations typically take constant time apart from lock contention or waiting. Each queued item is in a node. The default capacity is Integer.MAX_VALUE and can exhaust heap much earlier. Compare actual allocation rate, throughput and latency against an array-backed queue.

Interview questions:

What allows ordinary put and take paths to contend less?

Separate end locks coordinate insertion and removal, with count and signals connecting them.

PriorityBlockingQueue

Definition:

An unbounded blocking consumer queue backed by a priority heap.

Explanation:

Use this when the next consumer should take the highest-ranked available item. The example uses smaller numeric priority first and a monotonic sequence to break ties explicitly.

Illustration image:

The root ranks first. Other array positions are not a sorted traversal. An explicit sequence makes equal-priority jobs deterministic. Binary heap and the next removalurgent-1urgent-2normaltake()Only the root can leave nextOrder by priority, then sequence
The root ranks first. Other array positions are not a sorted traversal. An explicit sequence makes equal-priority jobs deterministic.

Example:

Java · runnable lab excerpt
record Job(String name, int priority, long sequence) {}

static void priorityBlockingQueue() throws InterruptedException {
    var queue = new PriorityBlockingQueue<>(3, Comparator.comparingInt(Job::priority)
        .thenComparingLong(Job::sequence));
    queue.put(new Job("normal", 5, 0));
    queue.put(new Job("urgent-1", 1, 1));
    queue.put(new Job("urgent-2", 1, 2));
    check(queue.take().name().equals("urgent-1"));
    check(queue.take().name().equals("urgent-2"));
    check(queue.take().name().equals("normal"));
}

Expected result. Take returns urgent-1, urgent-2, then normal. The tie-breaker makes equal priorities predictable.

Internal working:

Inside OpenJDK 21

The queue stores an array-backed binary heap. A parent ranks no lower than its children under the chosen ordering; minimum is at the root. Offer typically sifts a value up. Take replaces the root with the last element and sifts down. A lock protects heap changes, and a notEmpty condition lets consumers await work.

Trace the example

Urgent-1 and urgent-2 outrank normal. Their equal priority is resolved by sequence, so urgent-1 is taken first. An iterator does not visit heap values in removal order. A new high-priority task cannot preempt a task already removed by a consumer.

Cost and limits

Heap insertion and removal are O(log n), apart from growth and locking. The constructor's initial capacity is not a bound. Producers do not wait for spare logical capacity; add separate admission control to prevent heap growth.

Interview questions:

How do you enforce FIFO for equal priorities?

Add a monotonically increasing sequence to the comparator; equality in priority alone does not guarantee FIFO.

DelayQueue

Definition:

An unbounded queue whose elements become retrievable when their delays expire.

Explanation:

Use DelayQueue to make work available only after its expiry. Think of a heap ordered by deadline, where removal is gated by the head being due rather than by the presence of any item.

Illustration image:

The root ranks first. Other array positions are not a sorted traversal. A positive delay prevents even the root from being removed. Deadline heap and expiry gateduelaterlatestreadyOnly the root can leave nextOrder by deadline
The root ranks first. Other array positions are not a sorted traversal. A positive delay prevents even the root from being removed.

Example:

Java · runnable lab excerpt
record Reminder(String name, long dueNanos) implements Delayed {
    @Override public long getDelay(TimeUnit unit) {
        return unit.convert(dueNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
    }
    @Override public int compareTo(Delayed other) {
        return Long.compare(dueNanos, ((Reminder) other).dueNanos);
    }
}

static void delayQueue() throws InterruptedException {
    var reminders = new DelayQueue<Reminder>();
    long now = System.nanoTime();
    reminders.add(new Reminder("later", now + TimeUnit.MINUTES.toNanos(1)));
    reminders.add(new Reminder("due", now - 1));
    check(reminders.poll(1, TimeUnit.SECONDS).name().equals("due"));
    check(reminders.peek().name().equals("later"));
    check(reminders.poll() == null);
}

Expected result. Poll returns due, peek observes later, and the second poll returns null while later is ineligible.

Internal working:

Inside OpenJDK 21

A priority queue stores Delayed items. A lock and condition guard the queue, and a leader–follower arrangement lets one waiting thread time its wait to the earliest deadline. When a new earlier deadline is inserted, waiting behavior is reconsidered. Other consumers may wait without independently timing the same head.

Trace the example

A due reminder can be removed immediately. A later reminder remains visible to peek, while poll returns null because the head still has a positive delay. Use System.nanoTime differences for elapsed-time deadlines and keep Delayed.compareTo consistent with getDelay.

Cost and limits

The queue is unbounded; track outstanding delayed jobs separately when demand is untrusted. Use a ScheduledExecutorService if you want scheduling plus worker execution in one abstraction. DelayQueue itself only gates availability.

Interview questions:

Can peek show a value while poll returns null?

Yes. peek can see the earliest item before it is eligible for removal.

SynchronousQueue

Definition:

A zero-capacity queue that directly matches a producer and a consumer.

Explanation:

Use this for a rendezvous: a producer hands an item to a consumer without storing a backlog. A successful put or timed offer means a counterpart participated in the handoff.

Illustration image:

A complementary consumer receives the item directly. There is no storage slot for work without a receiver. Rendezvous with zero stored itemsPCmatchProducerConsumerNo consumer → immediate offer fails
A complementary consumer receives the item directly. There is no storage slot for work without a receiver.

Example:

Java · runnable lab excerpt
static void synchronousQueue() throws Exception {
    var queue = new SynchronousQueue<String>();
    check(!queue.offer("no receiver"));
    try (var worker = Executors.newVirtualThreadPerTaskExecutor()) {
        var consumer = worker.submit(() -> queue.poll(2, TimeUnit.SECONDS));
        check(queue.offer("handoff", 2, TimeUnit.SECONDS));
        check("handoff".equals(consumer.get(2, TimeUnit.SECONDS)));
        check(queue.isEmpty());
    }
}

Expected result. The first offer returns false. The timed handoff returns true, and the consumer receives handoff.

Internal working:

Inside OpenJDK 21

Producers and consumers register complementary requests and attempts match them directly. The 21 implementation has a nonfair stack-like strategy and a fair FIFO strategy. Waiting threads can park and later wake for a match, timeout or interruption; the queue never retains an available buffered item.

Trace the example

Immediate offer fails with no receiver. After a consumer starts waiting, timed offer can rendezvous and deliver handoff. isEmpty remains true in the collection view even during coordination because waiting requests are not buffered elements.

Cost and limits

Choose this for direct work transfer where blocking or rejection is intentional. As a ThreadPoolExecutor queue it can trigger worker growth or rejection instead of building a queue. Handoff completion is not proof that application processing completed.

Interview questions:

When can an immediate offer succeed?

Only when it can match a waiting consumer. There is no buffered storage for an unmatched offer.

LinkedTransferQueue

Definition:

An unbounded linked queue supporting ordinary enqueueing and producer-to-consumer receipt.

Explanation:

Use this when most messages may queue but selected messages must wait for a receiver. A TransferQueue gives both semantics in one API.

Illustration image:

A complementary consumer receives the item directly. Ordinary offer can buffer a value; tryTransfer without a receiver returns false. Queued data or direct receiptPCmatchProducerConsumerbuffered dataoffer can queue
A complementary consumer receives the item directly. Ordinary offer can buffer a value; tryTransfer without a receiver returns false.

Example:

Java · runnable lab excerpt
static void linkedTransferQueue() throws Exception {
    TransferQueue<String> queue = new LinkedTransferQueue<>();
    check(!queue.tryTransfer("no receiver"));
    check(queue.offer("buffered"));
    check(queue.take().equals("buffered"));
    try (var worker = Executors.newVirtualThreadPerTaskExecutor()) {
        var consumer = worker.submit(() -> queue.poll(2, TimeUnit.SECONDS));
        check(queue.tryTransfer("accepted", 2, TimeUnit.SECONDS));
        check("accepted".equals(consumer.get(2, TimeUnit.SECONDS)));
    }
}

Expected result. Immediate tryTransfer fails with no receiver; ordinary offer buffers; timed transfer succeeds with a consumer.

Internal working:

Inside OpenJDK 21

A linked dual queue represents waiting data and waiting requests. Complementary operations match via CAS; if a match is absent, ordinary enqueue may add a data node and an awaiting consumer can add a request. Synchronous transfer waits for a consumer match. Timeouts and cancellation clean up or bypass abandoned nodes.

Trace the example

tryTransfer returns false rather than enqueuing when no consumer is waiting. offer enqueues buffered even without a consumer. Timed tryTransfer can wait for a match, after which the receiver takes accepted. Matching confirms receipt, not completed business processing.

Cost and limits

The queue is unbounded. Use offer for asynchronous producer decoupling, transfer for receipt synchronization, and timed variants when a deadline matters. Counters such as waiting-consumer count are observational, not admission locks.

Interview questions:

Does transfer completion mean the business work finished?

No. It indicates receipt by a consumer, not completion of processing.

LinkedBlockingDeque

Definition:

An optionally bounded linked queue supporting blocking work at either end.

Explanation:

Choose a blocking deque when both ends matter and the application needs an optional hard capacity. For example, a small worker queue can take from the front and put urgent local work at the front.

Illustration image:

Two-way links support both ends. The configured capacity and condition signals control admission. Linked deque with bounded admissionFront / headBack / tailABCLock + notEmpty / notFullEither end can remove
Two-way links support both ends. The configured capacity and condition signals control admission.

Example:

Java · runnable lab excerpt
static void linkedBlockingDeque() throws InterruptedException {
    BlockingDeque<String> queue = new LinkedBlockingDeque<>(2);
    queue.putLast("normal");
    queue.putFirst("urgent");
    check(!queue.offerLast("over capacity"));
    check(queue.takeFirst().equals("urgent"));
    check(queue.takeLast().equals("normal"));
}

Expected result. When full the extra offer fails; the two removals return urgent then normal.

Internal working:

Inside OpenJDK 21

Doubly linked nodes add or remove at both endpoints under one ReentrantLock. A count enforces the configured capacity. notEmpty and notFull signal waiters after endpoint changes. Unlike LinkedBlockingQueue, this implementation coordinates both endpoints through one lock.

Trace the example

A normal task goes to the back and an urgent task goes to the front. A third offer fails at capacity two. takeFirst gets the urgent task, and takeLast gets the normal task. Deque priority policies can starve normal work under repeated front insertions.

Cost and limits

Endpoint operations are constant time aside from contention and waits. Each entry allocates a node, and the default capacity is very large. Set capacity and fairness at the application scheduling level when ordinary work needs latency guarantees.

Interview questions:

What risk comes with repeatedly inserting urgent work at the front?

Older normal work can starve. Define a fairness or scheduling policy in the application.

Related interfaces

Program against the narrowest interface that exposes the required behavior. The concrete type still decides the actual capacity, ordering policy and how the operation coordinates threads.

ConcurrentMap

Definition:

An interface for maps with documented concurrent and conditional update operations.

Explanation:

Atomic per-key insert, replace and conditional remove. The type does not make multiple calls or multiple keys a transaction.

Illustration image:

Conditional replace ensures that only the observed value is updated. ConcurrentMap contract in this exampleorders=1replace(1, 2)orders=2
Conditional replace ensures that only the observed value is updated.

Example:

Java · interface example
ConcurrentMap<String, Integer> counts = new ConcurrentHashMap<>();
check(counts.putIfAbsent("orders", 1) == null);
check(counts.replace("orders", 1, 2));

Internal working:

Conditional replace ensures that only the observed value is updated.

Interview questions:

Can two independent ConcurrentMap calls be treated as one transaction?

No. Use a documented atomic operation or a broader coordination boundary.

ConcurrentNavigableMap

Definition:

An interface combining concurrent map operations with sorted navigation and range views.

Explanation:

ConcurrentMap combined with sorted navigation and backed range views. Order and comparator consistency matter.

Illustration image:

ceilingKey(9) returns 10 because 10 is the smallest registered key at least 9. ConcurrentNavigableMap contract in this examplequery 9ceiling searchkey 10
ceilingKey(9) returns 10 because 10 is the smallest registered key at least 9.

Example:

Java · interface example
ConcurrentNavigableMap<Integer, String> book = new ConcurrentSkipListMap<>();
book.put(10, "ten");
check(book.ceilingKey(9) == 10);

Internal working:

ceilingKey(9) returns 10 because 10 is the smallest registered key at least 9.

Interview questions:

Can a caller mutate any key through a range view?

No. Updates through the view are constrained to its declared bounds.

BlockingQueue

Definition:

A queue interface adding interruptible and deadline-bounded waiting operations.

Explanation:

Four operation families: add/remove throw where offer/poll return status; put/take wait interruptibly; timed offer/poll wait at most the specified duration. peek returns null on empty, whereas element throws.

Illustration image:

The bounded queue accepts A, and the consumer takes A. BlockingQueue contract in this exampleproducer Abounded bufferconsumer A
The bounded queue accepts A, and the consumer takes A.

Example:

Java · interface example
BlockingQueue<String> fifo = new ArrayBlockingQueue<>(1);
check(fifo.offer("A", 100, TimeUnit.MILLISECONDS));
check(fifo.take().equals("A"));

Internal working:

The bounded queue accepts A, and the consumer takes A.

Interview questions:

How do add, offer and put differ on a full bounded queue?

add throws; offer returns false; put waits interruptibly for capacity.

BlockingDeque

Definition:

A blocking queue interface with operations at both ends.

Explanation:

BlockingQueue with operations at both ends, including putFirst and takeLast. A queue method without an endpoint uses the corresponding FIFO end.

Illustration image:

The front insertion can be paired with a removal at the opposite end. BlockingDeque contract in this exampleinsert firstdeque endpointremove last
The front insertion can be paired with a removal at the opposite end.

Example:

Java · interface example
BlockingDeque<String> deque = new LinkedBlockingDeque<>(1);
deque.putFirst("urgent");
check(deque.takeFirst().equals("urgent"));

Internal working:

The front insertion can be paired with a removal at the opposite end.

Interview questions:

Which ends does ordinary queue-style put and take use?

put inserts at the tail and take removes from the head.

TransferQueue

Definition:

A blocking queue interface adding operations that coordinate consumer receipt.

Explanation:

BlockingQueue with tryTransfer and transfer. Immediate tryTransfer succeeds only with a waiting receiver; transfer may block until receipt. Ordinary offer can buffer in a supporting implementation.

Illustration image:

Without a receiver, tryTransfer returns false; offer accepts a buffered item. TransferQueue contract in this exampletryTransferno receiverfalse
Without a receiver, tryTransfer returns false; offer accepts a buffered item.

Example:

Java · interface example
TransferQueue<String> transfers = new LinkedTransferQueue<>();
check(!transfers.tryTransfer("needs receiver"));
check(transfers.offer("can wait in queue"));

Internal working:

Without a receiver, tryTransfer returns false; offer accepts a buffered item.

Interview questions:

How does tryTransfer without a timeout differ from offer?

tryTransfer needs a waiting receiver. An implementation such as LinkedTransferQueue can buffer with offer.