Java Concurrent Collections: Maps and Queues

Java concurrent collections deep dive: ConcurrentHashMap, BlockingQueue, CopyOnWriteArrayList, ConcurrentLinkedQueue, and choosing the right structure.

published: reading time: 24 min read author: Geek Workbench
Quick Summary

Java concurrent collections deep dive: ConcurrentHashMap, BlockingQueue, CopyOnWriteArrayList, ConcurrentLinkedQueue, and choosing the right structure.

Java Concurrent Collections: ConcurrentHashMap, BlockingQueue, and More

A synchronized wrapper guards individual map operations with a shared lock. Under contention, callers may wait for that lock. Java’s concurrent collections provide different guarantees and coordination patterns; choose one based on the operations your code needs.

Introduction

A synchronized wrapper serializes calls that use its shared lock. Concurrent implementations can allow more overlap, but their APIs and implementation details differ. For example, ConcurrentHashMap supports concurrent retrievals and updates; it does not make a multi-step sequence atomic unless you use an operation that provides that guarantee.

The concurrent collections solve different problems. ConcurrentHashMap supports concurrent map operations without a table-wide lock; BlockingQueue can coordinate producers and consumers through blocking operations; CopyOnWriteArrayList copies its array on mutation and suits collections read far more often than they change. The API is the stable contract. Internal implementation details vary by JDK release.

This post compares ConcurrentHashMap, blocking and non-blocking queues, CopyOnWriteArrayList, and LongAdder. It focuses on their API guarantees, queue bounds, and the costs of contention and copying. Internal details vary by JDK release.

ConcurrentHashMap

Why Not Just Use synchronizedMap?

// This serializes all access - one thread at a time
Map<String, Integer> syncMap = Collections.synchronizedMap(new HashMap<>());
syncMap.put("key", 1); // Only one thread can touch this at a time

// ConcurrentHashMap allows concurrent reads and writes
ConcurrentHashMap<String, Integer> chm = new ConcurrentHashMap<>();
chm.put("key", 1); // Multiple threads can write concurrently

How ConcurrentHashMap Works

The API does not promise segments or a fixed lock count. In the OpenJDK 21 implementation, retrievals generally do not lock; updates use atomic table operations and may synchronize on a bin when needed. Resizing and collisions add more detail, so treat this as an implementation note for OpenJDK 21, not a contract for every JVM. The Java 21 API specifies the observable guarantees.

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

// Atomic operations - no synchronized needed
map.putIfAbsent("key", 0);  // Put only if absent
map.replace("key", 0, 1);    // Replace only if current value matches
map.computeIfAbsent("key", k -> expensiveComputation()); // Lazy init
map.merge("key", 1, Integer::sum); // Combine values

// Bulk operations - iterate without ConcurrentModificationException
map.forEach(1, (k, v) -> System.out.println(k + "=" + v));
map.search(1, (k, v) -> v > 100 ? k : null); // Search with concurrency

Iteration in ConcurrentHashMap

Unlike regular iterators, ConcurrentHashMap iterators are weakly consistent:

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("a", 1);
map.put("b", 2);

// This won't throw ConcurrentModificationException
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    // May or may not see updates that happened during iteration
    // but won't repeat any entries
    System.out.println(entry.getKey() + "=" + entry.getValue());
}

The iterator may reflect changes that occurred during iteration, but it won’t throw CME and won’t revisit entries.

Null Handling

Important: ConcurrentHashMap does not allow null keys or values. This was a deliberate design decision to avoid ambiguity in concurrent contexts.

map.put(null, 1);  // NullPointerException
map.get(null);      // NullPointerException

If you need null support, consider Collections.synchronizedMap() or a plain map with external synchronization.

BlockingQueue

BlockingQueue adds blocking operations for producer-consumer patterns. Producers block when the queue is full, consumers block when empty.

BlockingQueue<Order> queue = new LinkedBlockingQueue<>(1000); // Bounded

// Producer side - blocks if queue is full
public void enqueue(Order order) throws InterruptedException {
    queue.put(order); // Blocks until space available
}

// Consumer side - blocks if queue is empty
public Order dequeue() throws InterruptedException {
    return queue.take(); // Blocks until item available
}

// Non-blocking alternatives
queue.offer(order, 1, TimeUnit.SECONDS); // Wait up to 1 second
queue.poll(1, TimeUnit.SECONDS);          // Wait up to 1 second

Bounded vs Unbounded Queues

// Unbounded - grows as needed, can cause OOM
LinkedBlockingQueue<Order> unbounded = new LinkedBlockingQueue<>();

// Bounded - limits memory usage
LinkedBlockingQueue<Order> bounded = new LinkedBlockingQueue<>(1000);

// Array-based - more predictable performance
ArrayBlockingQueue<Order> arrayQueue = new ArrayBlockingQueue<>(1000);

// Priority-based - keeps elements sorted
PriorityBlockingQueue<Order> priorityQueue = new PriorityBlockingQueue<>();

Implementations

Java ships five BlockingQueue implementations. Each one trades off memory, throughput, and coordination semantics differently. The table below summarizes the key dimensions, and the sections that follow dig into the ones that cause the most confusion.

Implementation Bounded Notes
LinkedBlockingQueue Optional Most common
ArrayBlockingQueue Yes Fixed size, array-backed
PriorityBlockingQueue No Priority queue
DelayQueue No Elements with delays
SynchronousQueue Yes (capacity 0) Handoff - no storage

SynchronousQueue for Handoffs

SynchronousQueue has no capacity - a put must wait for a take and vice versa:

SynchronousQueue<Task> handoff = new SynchronousQueue<>();

// Producer
new Thread(() -> {
    try {
        // Blocks until consumer takes
        handoff.put(task);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}).start();

// Consumer
Task task = handoff.take(); // Blocks until producer puts

Use this when you want direct handoff between threads without buffering.

CopyOnWriteArrayList

CopyOnWriteArrayList creates a fresh copy on every write. Reads are lock-free and never see partial modifications.

CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();

// Readers - never block, never see partial writes
public void notifyListeners() {
    for (Listener listener : listeners) {
        listener.onEvent(); // Safe iteration
    }
}

// Writers - expensive, but no readers ever blocked
public void addListener(Listener listener) {
    listeners.add(listener); // New copy created
}

When to Use CopyOnWriteArrayList

Good for:

  • Listener lists where reads vastly outnumber writes
  • Cached configurations read frequently but updated rarely
  • Situations where iteration must not throw CME

Bad for:

  • Write-heavy workloads (every write copies the entire array)
  • Large lists (copying costs grow with size)
  • When you need to modify during iteration (use iterator.remove())

When NOT to Use Concurrent Collections

Concurrent collections are not always the right call, and using them reflexively creates problems. If your collection is only ever accessed from one thread — which is common in simpler applications or narrow scopes — a plain ArrayList, HashMap, or ArrayDeque is faster and introduces no concurrency overhead. The lock-free algorithms in ConcurrentHashMap and its siblings perform memory ordering operations on every read and write, and that cost is wasted if no other thread is actually competing.

Snapshot isolation catches people off guard. Concurrent collection iterators are weakly consistent: they may or may not reflect updates that happened during iteration, and they will not throw ConcurrentModificationException — but they also will not give you a point-in-time snapshot. If you need consistent iteration over a collection’s state, you must copy it first (new ArrayList<>(source)). Making decisions based on weakly consistent iteration is how subtle correctness bugs creep in.

computeIfAbsent runs its mapping function atomically for a missing key in ConcurrentHashMap; other updates may wait while that computation is in progress. Keep the function short and avoid network calls or other slow work inside it. A cache library can provide loading, expiration, and other policies when those are needed. For frequently updated counters, LongAdder can reduce contention compared with AtomicLong; benchmark the choice for the workload. See Java Atomics and VarHandle for related APIs.

ConcurrentLinkedQueue and Deque

Lock-free linked structures for high throughput:

ConcurrentLinkedQueue<Task> queue = new ConcurrentLinkedQueue<>();
ConcurrentLinkedDeque<Task> deque = new ConcurrentLinkedDeque<>();

// Queue operations
queue.offer(task);      // Add to tail
Task task = queue.poll(); // Remove from head

// Deque operations - can operate on both ends
deque.offerFirst(task);
deque.offerLast(task);
Task first = deque.pollFirst();
Task last = deque.pollLast();

Choosing a Concurrent Collection

// Need a map with concurrent access?
// - High read, low write: ConcurrentHashMap
// - Need ordering: ConcurrentSkipListMap

// Need a queue for producer-consumer?
// - Bounded: LinkedBlockingQueue or ArrayBlockingQueue
// - Handoff (no buffer): SynchronousQueue
// - Priority-based: PriorityBlockingQueue

// Need a list with safe iteration?
// - Read-heavy, few updates: CopyOnWriteArrayList
// - Otherwise: ConcurrentLinkedQueue for queue semantics

// Need a set?
// - ConcurrentHashMap.newKeySet() - most efficient
// - ConcurrentSkipListSet - if ordering needed

Architecture Diagram

ConcurrentMap

The ConcurrentMap interface extends Map with thread-safety and atomicity guarantees. ConcurrentHashMap is a general-purpose choice when many threads access a map. Its API does not expose or promise the internal locking layout; see the version-pinned OpenJDK 21 note above before using implementation details to reason about contention.

ConcurrentSkipListMap is the ordered alternative. It maintains keys in sorted order and supports range operations like subMap, headMap, and tailMap that a hash map cannot provide. Performance is O(log n) for most operations. If you need ordering guarantees alongside concurrent access, this is your choice.

graph TD
    subgraph ConcurrentMap
        CM1[ConcurrentHashMap] --> CM2[Unordered concurrent map]
        CM3[ConcurrentSkipListMap] --> CM4[Sorted concurrent map]
    end

BlockingQueue Overview

BlockingQueue extends Queue with operations that wait for the queue to be non-empty (on poll) or have available capacity (on put). This is the natural fit for producer-consumer patterns: producers block when the queue is full, consumers block when it is empty.

Four implementations cover most coordination scenarios. LinkedBlockingQueue is the most commonly used — linked-node based with optional capacity bounds, so it works as both a bounded and unbounded queue. ArrayBlockingQueue is array-backed with fixed capacity and better cache locality, but no dynamic growth. PriorityBlockingQueue orders elements by comparator or natural order, which is useful for priority scheduling where insertion order does not matter. DelayQueue holds elements that implement Delayed — an element only comes out of the queue via take() once its delay has expired, making it suitable for scheduled task executors.

SynchronousQueue has no storage capacity at all. A put() must wait for a take() and vice versa, which means zero buffering. Thread pools use it internally for direct handoff between threads.

graph TD
    subgraph BlockingQueue
        BQ1[LinkedBlockingQueue] --> BQ5[Bounded/unbounded linked]
        BQ2[ArrayBlockingQueue] --> BQ6[Fixed array, bounded]
        BQ3[PriorityBlockingQueue] --> BQ7[Heap, priority ordered]
        BQ4[SynchronousQueue] --> BQ8[No storage, direct handoff]
    end

CopyOnWrite

CopyOnWriteArrayList is the only implementation in this category. Every mutative operation — add, remove, set — copies the entire underlying array. Iterators hold a reference to the snapshot taken at creation time and never change it, which is why iteration never throws ConcurrentModificationException and never blocks readers.

Writers pay for the array copy, so this collection fits best when reads are frequent and writes are rare. Listener lists and stable configuration snapshots are common examples. If writes are frequent or the list is large, measure allocation and garbage-collection costs before choosing it.

graph TD
    subgraph CopyOnWrite
        COW1[CopyOnWriteArrayList] --> COW2[Full copy on write]
    end

LockFree

Lock-free collections use atomic Compare-And-Set (CAS) operations instead of locks. ConcurrentLinkedQueue and ConcurrentLinkedDeque are the two linked-structure implementations, both built on CAS with no internal locking.

ConcurrentLinkedQueue is a FIFO queue backed by a singly-linked structure. offer() appends to the tail using CAS, and poll() removes from the head. The algorithm is optimistic: it retries if another thread modified the target node between the read and the CAS attempt. Under moderate contention this works well; under heavy contention on the same queue, retries pile up.

ConcurrentLinkedDeque supports insertion and removal at both ends, which can suit work-stealing patterns. Both linked collections are unbounded and do not wait for queue capacity, unlike bounded blocking queues. Their lock-free algorithms may retry under contention, so “non-blocking” does not mean every call completes in a fixed amount of time.

graph TD
    subgraph LockFree
        LF1[ConcurrentLinkedQueue] --> LF3[CAS operations]
        LF2[ConcurrentLinkedDeque] --> LF3
    end

Production Failure Scenarios

Scenario 1: Memory Explosion with CopyOnWriteArrayList

Illustrative scenario: a logging list receives frequent writes while retaining many entries. Each mutation copies the array, so the work and allocation grow with the list size. Under sustained writes, this can add substantial allocation and garbage-collection pressure; measure the actual workload before choosing a replacement.

The fix is to use a concurrent queue instead. ConcurrentLinkedQueue uses lock-free CAS operations and never copies the full array on writes.

// BROKEN - writing frequently causes memory churn
CopyOnWriteArrayList<LogMessage> logs = new CopyOnWriteArrayList<>();
executor.scheduleAtFixedRate(() -> {
    logs.add(new LogMessage("periodic update")); // Copies entire list every second!
}, 1, 1, TimeUnit.SECONDS);

// Alternative when FIFO queue semantics fit the workload
ConcurrentLinkedQueue<LogMessage> logs = new ConcurrentLinkedQueue<>();

Scenario 2: BlockingQueue Without Capacity

A LinkedBlockingQueue with no explicit capacity uses a very large effective limit (Integer.MAX_VALUE), so it can grow until memory pressure becomes a problem if producers outpace consumers. In that configuration, producers are unlikely to get useful backpressure before the process runs low on memory.

Choose a capacity from the amount of queued work the service can tolerate, and decide whether producers should block, time out, or reject work when it is full. A bound limits queued items; it does not by itself prevent overload if callers ignore backpressure.

// BROKEN - unbounded queue can grow without limit
BlockingQueue<Task> queue = new LinkedBlockingQueue<>();
// If producers outpace consumers, this grows until OOM

// FIXED - always set reasonable capacity
BlockingQueue<Task> queue = new LinkedBlockingQueue<>(1000); // illustrative bound; size for your workload

Scenario 3: ConcurrentHashMap and null Values

ConcurrentHashMap deliberately rejects null for both keys and values. This was a deliberate design choice, not an oversight. It eliminates an entire class of ambiguity in concurrent programs. When map.get(key) returns null, you need to know whether the key was absent or whether the value stored for that key was actually null. In a concurrent setting, another thread might have removed the value between your check and your read, so a null check-then-get is itself racy. By forbidding nulls, ConcurrentHashMap makes the return value unambiguous: null always means the key is absent.

If you try to store a null value, you get an immediate NullPointerException rather than silent data loss or subtle corruption. The same exception fires on putIfAbsent, get, and any other method that would need to distinguish a missing key from a null value.

// BROKEN - NPE will occur
ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap<>();
cache.putIfAbsent("user", null); // NPE

// FIXED - use a different marker value
cache.putIfAbsent("user", NULL_PLACEHOLDER);

Trade-off Table

Collection Reads Writes Memory Use When
ConcurrentHashMap Generally non-blocking reads Atomic, contention-dependent updates Low General concurrent map
Hashtable Lock whole Lock whole Medium Legacy compatibility
synchronizedMap Lock whole Lock whole Medium Need null keys
CopyOnWriteArrayList Lock-free Expensive copy High per write Read-heavy, few writes
LinkedBlockingQueue Blocking Blocking Moderate Producer-consumer
ArrayBlockingQueue Blocking Blocking Fixed Bounded producer-consumer
SynchronousQueue Blocking Blocking None Direct handoff

Implementation Snippets

Producer-Consumer with BlockingQueue

The OrderProcessor shows producer-consumer in practice. The constructor spins up a fixed thread pool, each consumer running processOrders in a loop that calls take() to wait for work. submitOrder calls put(), which blocks when the queue is full — the 500-item cap gives you backpressure so producers cannot flood memory. On shutdown, shutdownNow interrupts the consumers, the InterruptedException fires, and the loop breaks cleanly.

public class OrderProcessor {
    private final BlockingQueue<Order> orders = new LinkedBlockingQueue<>(500);
    private final ExecutorService consumerPool;

    public OrderProcessor(int consumerCount) {
        consumerPool = Executors.newFixedThreadPool(consumerCount);
        for (int i = 0; i < consumerCount; i++) {
            consumerPool.submit(this::processOrders);
        }
    }

    public void submitOrder(Order order) throws InterruptedException {
        orders.put(order);
    }

    private void processOrders() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                Order order = orders.take();
                process(order);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }
    }

    public void shutdown() {
        consumerPool.shutdownNow();
    }
}

Cache with ConcurrentHashMap

This example uses computeIfAbsent to lazily initialize a cache entry. For a missing key, the mapping function computes and installs a non-null value atomically. Keep that function short: the Java 21 API warns that other updates may be blocked while it runs. For network or database loaders, use a cache library with an explicit loading policy rather than making the map operation perform slow I/O.

public class DataCache<K, V> {
    private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<>();
    private final Function<K, V> loader;

    public DataCache(Function<K, V> loader) {
        this.loader = loader;
    }

    public V get(K key) {
        return cache.computeIfAbsent(key, loader);
    }

    public void invalidate(K key) {
        cache.remove(key);
    }

    public void clear() {
        cache.clear();
    }
}

Observability Checklist

  • Do you know which collections allow null values?
  • Are your bounded queues actually bounded?
  • Can you detect queue saturation in monitoring?
  • Are you using CopyOnWriteArrayList for read-heavy workloads only?
  • Do you have appropriate queue capacity for backpressure?
  • Are consumers faster than producers on average?

Security Notes

Collections can expose data if not properly secured:

  • ConcurrentHashMap doesn’t prevent unauthorized read access within the same JVM
  • Use defensive copies when passing collections to untrusted code
  • Consider immutability wrappers for shared data: Collections.unmodifiableMap()

Common Pitfalls / Anti-Patterns

  1. Using synchronized collections under load: They’ll serialize access and kill throughput
  2. CopyOnWriteArrayList for write-heavy use: Every write copies the entire array
  3. Unbounded queues: Can cause OutOfMemoryError
  4. Assuming iteration is point-in-time: In concurrent collections, it’s weakly consistent
  5. Ignoring null policies: ConcurrentHashMap rejects nulls
  6. Queue capacity mis-tuning: Too small causes blocking, too large wastes memory

Quick Recap Checklist

  • ConcurrentHashMap provides thread-safe map operations; consult the JDK API for its guarantees
  • BlockingQueue blocks producers on full queue, consumers on empty
  • CopyOnWriteArrayList copies entire array on write, great for read-heavy
  • SynchronousQueue is zero-capacity handoff, not a queue
  • Bounded queues provide backpressure
  • ConcurrentHashMap doesn’t allow null keys/values
  • Iteration is weakly consistent in concurrent collections

Interview Questions

1. What does the ConcurrentHashMap API guarantee about concurrent access?

The API provides thread-safe map operations. Retrievals generally do not block, and its iterators are weakly consistent rather than fail-fast. Those are API guarantees; segment counts and locking layouts are not. For a concrete implementation example, the note above describes OpenJDK 21.

2. When would you use CopyOnWriteArrayList over regular ArrayList?

Use CopyOnWriteArrayList when reads vastly outnumber writes and you need to iterate without ConcurrentModificationException. Classic use case: listener/callback lists that are read frequently but modified rarely.

Don't use it if writes are frequent - every add() and remove() copies the entire array, which gets expensive fast. For most concurrent scenarios, ConcurrentLinkedQueue or ConcurrentHashMap.newKeySet() are better choices.

3. What is the difference between BlockingQueue and ConcurrentLinkedQueue?

BlockingQueue operations block: put() blocks when full, take() blocks when empty. This makes it ideal for producer-consumer patterns where consumers need to wait for work.

ConcurrentLinkedQueue is unbounded and does not wait for capacity. Its CAS-based operations can retry under contention, so it has no portable throughput advantage over a blocking queue. Use it when non-blocking queue operations fit the application and you have a separate plan for bounding queued work.

4. Why does ConcurrentHashMap not allow null keys or values?

The decision was made to eliminate ambiguity in concurrent contexts. If map.get(key) returns null, you can't tell if the key wasn't present or if the value was actually null. With concurrent access, another thread might have just removed the value.

In single-threaded maps you can check with containsKey(), but in concurrent scenarios this check-then-get is itself racy. Forcing non-null values eliminates this ambiguity.

5. How do you choose between ArrayBlockingQueue and LinkedBlockingQueue?

ArrayBlockingQueue stores elements in a fixed-size array. LinkedBlockingQueue uses linked nodes and separate producer and consumer locks; without an explicit capacity, its limit is Integer.MAX_VALUE. Both preserve FIFO item order. Compare their memory use and throughput under the expected workload, and choose a capacity that sets useful backpressure.

6. What happens when multiple threads call ConcurrentHashMap.computeIfAbsent for the same missing key?

The mapping function is applied atomically for a missing key, so concurrent calls do not all compute the same key's value. Other updates may wait while the computation is running. Keep the function short; use a cache library when loading requires I/O, expiration, or refresh policies.

7. When should you use SynchronousQueue over other BlockingQueue implementations?

SynchronousQueue has capacity zero—it doesn't actually store elements. A put() must wait for a take(), and vice versa. This produces direct handoff between threads with no buffering.

Use it when you want true handoff semantics: producer and consumer must meet at the same time. This is useful for thread pools that execute tasks submitted by callers directly (Executors.newCachedThreadPool() uses a SynchronousQueue internally), or for heavyweight tasks where buffering would waste memory.

8. Why does CopyOnWriteArrayList have a forEach that doesn't throw ConcurrentModificationException?

CopyOnWriteArrayList creates a fresh copy of its internal array on every write operation (add, remove). Iterators hold a reference to the immutable snapshot taken at creation time.

Since the snapshot never changes, the iterator never needs to modify it — reads proceed against a stable snapshot without synchronization. This avoids ConcurrentModificationException, but means iterators may reflect stale state if the list was modified after creation.

9. What is DelayQueue and when is it useful?

DelayQueue holds elements that implement the Delayed interface—each element has a getDelay(TimeUnit) method returning its remaining delay. An element only becomes available for removal (via take() or poll()) when its delay has expired.

Useful for scheduling tasks that should run after a fixed delay, such as retry with backoff, session expiration, or cached items with TTL. Elements with negative or zero delay are at the head and will be retrieved immediately.

10. What does it mean that concurrent collection iterators are "weakly consistent"?

Weakly consistent means the iterator may or may not reflect updates that occurred after iteration began, but it will never throw ConcurrentModificationException and will not repeat any elements.

In ConcurrentHashMap specifically, the iterator can tolerate concurrent modification, may proceed with stale reads, and won't block waiting for ongoing writes. This is a deliberate design trade-off for throughput—no locking on reads—which differs from the fail-fast iterators of synchronized collections.

11. How does ConcurrentHashMap handle contention in Java 8 and later?

The public API promises thread-safe operations, non-blocking retrievals in normal operation, and weakly consistent iteration; it does not promise a segment count. For the OpenJDK 21 implementation, retrievals generally avoid locking, while updates use CAS and may synchronize on a bin under contention. A hot key can still serialize updates to that key. Do not use these implementation details to predict another JDK’s exact behavior.

12. What is the stale data problem in concurrent collections and how does drainTo() address it?

Stale data refers to items that have been polled from a queue but represent state from before the poll operation began. In concurrent queues, poll() atomically removes and returns an element, but between the check for empty and the removal, state could change. drainTo() removes multiple elements in a single operation compared to repeated poll() calls, reducing the window where stale reads could occur in the consuming code. For queue monitoring, drainTo() batches removals which is more efficient than individual polls in a loop.

13. What is ConcurrentSkipListMap and how does it differ from ConcurrentHashMap?

ConcurrentSkipListMap keeps keys sorted and supports range views such as subMap; ConcurrentHashMap is a hash map with no ordering guarantee. Choose based on whether ordered traversal is part of the task, then benchmark the actual workload rather than relying on a blanket speed comparison. Neither API promises a particular internal locking algorithm.

14. Why does ConcurrentLinkedQueue use a lock-free algorithm and what are the implications?

ConcurrentLinkedQueue uses CAS-based operations and does not wait for capacity, because it is unbounded. Operations can retry under contention, and its iterators are weakly consistent. It does not provide the capacity bound or blocking backpressure of a bounded BlockingQueue; choose based on the application's queueing policy, not an assumed throughput ranking.

15. How does ArrayBlockingQueue differ from LinkedBlockingQueue in memory and performance characteristics?

ArrayBlockingQueue stores items in a fixed-size array and offers an optional fairness setting. LinkedBlockingQueue links nodes and has separate producer and consumer locks; specify a capacity if you need a practical bound. Both preserve FIFO queue order. Their throughput and memory costs depend on the workload, so benchmark the choice if it matters.

16. What is the difference between ConcurrentHashMap.putIfAbsent() and computeIfAbsent()?

putIfAbsent inserts a supplied value only if no mapping exists and returns the previous value. computeIfAbsent calls a mapping function when the key has no mapping and atomically installs a non-null result. On a contended key, callers may wait for the computation; keep mapping functions short and avoid network or other slow work inside them. The exact implementation details depend on the JDK, while the API contract is documented in the Java 21 ConcurrentHashMap API.

17. How does BlockingQueue's put() and offer() differ in blocking behavior?

put() blocks the calling thread indefinitely until space is available. offer() with timeout blocks for the specified duration before returning false. For bounded queues, use offer(timeout) to avoid indefinite blocking in producer threads. For producer-consumer patterns where blocking is expected, put() is simpler. offer() returns immediately with false for non-blocking producers that should fail fast rather than wait.

18. What is the implication of CopyOnWriteArrayList's copy-on-write semantics for memory usage under frequent writes?

CopyOnWriteArrayList copies its entire array on every write operation (add, remove, set). Under frequent writes, this causes constant full-array copying and garbage collection churn. For many writes per second, memory usage can spike dramatically. The copy overhead grows with list size. For write-heavy scenarios, CopyOnWriteArrayList is contraindicated - use concurrent collections like ConcurrentLinkedQueue or synchronized alternatives without copying. The read optimization only pays off when reads vastly outnumber writes (e.g., listener lists, configuration).

19. How does ConcurrentHashMap handle size() and isEmpty() correctly under concurrent modifications?

During concurrent updates, size(), isEmpty(), and similar aggregate observations may describe a transient state. The Java API advises using these results for monitoring or estimation rather than control flow while other threads mutate the map. If an exact count is part of an invariant, coordinate it explicitly instead of assuming a snapshot.

20. What is the appropriate use case for ConcurrentLinkedDeque vs ConcurrentLinkedQueue?

ConcurrentLinkedQueue is a single-ended queue (FIFO) supporting offer(), poll(), peek(). ConcurrentLinkedDeque is a double-ended queue allowing operations at both ends: offerFirst(), offerLast(), pollFirst(), pollLast(). Use ConcurrentLinkedQueue for simple producer-consumer with a single consumer-producer pair. Use ConcurrentLinkedDeque when you need LIFO (stack) semantics, multiple producers and consumers on different ends, or work-stealing patterns. Both are lock-free and non-blocking.

Further Reading

Conclusion

Choose a collection for the coordination you need: a concurrent map for keyed access, a blocking queue when producers and consumers need to coordinate, or a copy-on-write list when reads greatly outnumber writes. Bound queues when the system needs backpressure, and remember that ConcurrentHashMap rejects null keys and values. Continue with Java Atomics and VarHandle for lower-level coordination tools.

Category

Related Posts

Java atomics and VarHandle: Concurrency in Java 25

Learn Java 25 atomics: AtomicInteger, AtomicReference, CAS loops, LongAdder, VarHandle memory modes, and when to choose an atomic or lock.

#java #jvm #concurrency

Java Memory Model: Happens-Before, Volatile, Final Fields

Understanding happens-before guarantees, volatile field semantics, and final field safety in the Java Memory Model for correct concurrent code.

#java #jvm #concurrency

Java Concurrency: Executors, ForkJoinPool, Synchronizers

Master Java's java.util.concurrent: Executors, ForkJoinPool, CountDownLatch, CyclicBarrier, Phaser, and thread pool patterns for high-performance apps.

#java #jvm #concurrency