Quiz: Concurrent Collections in Java: ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue

Total: 8 questions

1. 

What happens when several threads modify an ArrayList or a HashMap at the same time?

The data gets corrupted, usually silently. If four threads each add 10,000 numbers to a shared ArrayList, it ends up with, say, 31,000 elements instead of 40,000, and sometimes one of the threads fails with ArrayIndexOutOfBoundsException right inside add().

The reason is how add() works: it reads size, grows the array if needed, writes the element into slot size and increments the counter. Two threads read the same size and write into the same slot - one element is lost; if one thread has grown the array while another is still writing into the old one, the index goes out of bounds. With HashMap, concurrent writes lose entries and corrupt bucket chains, and get() may fail to find a key that was just put.

ConcurrentModificationException is not protection against races but a check for "the collection was modified during iteration". A fail-fast iterator works only on a best-effort basis and may miss a write from another thread, so the absence of the exception proves nothing. The fix is Collections.synchronizedList, a collection from java.util.concurrent, or an immutable collection.

2. 

How does ConcurrentHashMap work since Java 8, and how does it differ from synchronizedMap and Hashtable?

ConcurrentHashMap is laid out like HashMap - an array of bins, a chain of nodes in each bin, a long chain turns into a tree - but it never locks the whole table:

  • a write into an empty bin is done with CAS, without a lock;
  • a write into a non-empty bin takes synchronized on the first node of that bin only;
  • get() does not lock at all and runs in parallel with writes;
  • when the table is resized, writing threads help move the bins instead of waiting.

Before Java 8 the map was split into segments (16 by default), each with its own ReentrantLock; the concurrencyLevel parameter is left over from that design and is now only a hint for the initial size.

Collections.synchronizedMap and Hashtable have one lock for the whole map, and even reads wait for a writing thread. All three are correct, and merge/compute*/putIfAbsent are atomic in all of them; the difference is scalability: eight threads updating eight different keys queue up on the wrapper but work at the same time on ConcurrentHashMap. Hashtable is for legacy code only.

3. 

What is a weakly consistent ConcurrentHashMap iterator, and how accurate is its size()?

A weakly consistent iterator:

  • never throws ConcurrentModificationException, even if the map is modified during iteration (including from the same thread);
  • visits every element that was in the map when the iterator was created, at most once;
  • may or may not reflect changes made after it was created.

It is not a snapshot like the CopyOnWriteArrayList iterator: it walks the live table.

size(), isEmpty() and containsValue() are exact only while nobody is modifying the map; under load they are estimates. size() returns an int, so for very large maps there is mappingCount() (Java 8), which returns a long. Do not build logic like "if size() exceeds N, remove an entry" on these values: the check and the removal are two operations, and the size is approximate.

4. 

How does computeIfAbsent differ from putIfAbsent in ConcurrentHashMap, and what rules apply to the computeIfAbsent function?

Both methods atomically put a value if the key is absent, but they differ in when the value is computed:

  • putIfAbsent(key, load(key)) - the argument is evaluated before the call, always, even if the key already exists. 100 threads call load() 100 times, and 99 results are thrown away.
  • computeIfAbsent(key, k -> load(k)) - the function is called only for an absent key and at most once: other threads with the same key wait and get the ready value. With the same 100 threads, load() runs once.

If the value is cheap or already available, putIfAbsent is fine; if it has to be loaded or computed, use computeIfAbsent. For counters, use merge(key, 1, Integer::sum) or compute().

Rules for the computeIfAbsent function:

  • keep it short - while it runs, the bin is locked and other writes to it wait;
  • it must not modify the same map: recursive memoization like memo.computeIfAbsent(n, k -> fib(k - 1) + fib(k - 2)) usually throws IllegalStateException: Recursive update on Java 9+ and could hang on Java 8;
  • nested computeIfAbsent calls on two maps in opposite order from two threads risk a deadlock;
  • if the function returns null, nothing is stored.
5. 

How do you get a thread-safe Set in Java?

There is no ConcurrentHashSet class in the JDK. The options are:

  • ConcurrentHashMap.newKeySet() (Java 8) - the default choice: the keys of a ConcurrentHashMap, contains() in O(1) without locking, no order, null not allowed.
  • ConcurrentSkipListSet - a sorted set, the counterpart of TreeSet: O(log n), with first() and headSet().
  • CopyOnWriteArraySet - for a dozen elements that are iterated often and changed rarely: linear contains(), insertion order is kept.
  • Collections.synchronizedSet(...) - one lock for everything; fine under light load or when you need to wrap a LinkedHashSet.

A useful property: add() returns true only if the element was not there, and in a thread-safe set this check is atomic. The code if (visited.add(url)) crawl(url); guarantees that each address is processed by exactly one thread, while a contains() + add() pair does not.

6. 

How does CopyOnWriteArrayList work, and when should you use it?

CopyOnWriteArrayList creates a new copy of its internal array on every modification (add, set, remove), while readers keep working with the old one without locks.

The iterator walks a snapshot of the array taken when it was created: it does not throw ConcurrentModificationException and does not see elements added afterwards. Changing a snapshot makes no sense, so the iterator methods remove(), set() and add() throw UnsupportedOperationException; remove elements through the list itself - remove(x) or removeIf(…). For "add if absent" there are atomic addIfAbsent() and addAllAbsent().

It fits when the list is read and iterated a lot but changed rarely: event listeners, configuration, allow-lists. It does not fit for collecting results or for task queues: n additions copy the array n times - O(n²) and a lot of garbage. If threads write often and iterate rarely, Collections.synchronizedList is better (iterate inside synchronized (list)).

7. 

What BlockingQueue implementations are there in Java, and how do they differ?

BlockingQueue is a thread-safe queue in which put() waits for free space and take() waits for an element. Every operation comes in four forms: throw an exception (add/remove), return a special value (offer → false, poll → null), block (put/take), or wait with a timeout. null is not allowed - NullPointerException.

  • ArrayBlockingQueue - bounded by the capacity given to the constructor, FIFO; a fast producer is stopped at put().
  • LinkedBlockingQueue - FIFO, separate locks for adding and removing. The default capacity is Integer.MAX_VALUE, so the queue is effectively unbounded and, if consumers fall behind, grows until OutOfMemoryError; set the capacity explicitly.
  • PriorityBlockingQueue - unbounded, ordered by Comparable/Comparator; the iterator ignores the priority order.
  • SynchronousQueue - zero capacity, hand-off: put() waits until another thread calls take(), and offer() without a waiting consumer returns false immediately.
  • DelayQueue - releases an element only after its delay has expired (Delayed).

There are also LinkedBlockingDeque (double-ended) and LinkedTransferQueue with its transfer() method.

8. 

Which thread-safe collection should replace HashMap, HashSet, TreeMap, ArrayList and a queue?

  • HashMap, Hashtable → ConcurrentHashMap: caches, counters, registries; null is not allowed.
  • HashSet → ConcurrentHashMap.newKeySet(); add() is a ready-made atomic "add if absent".
  • TreeMap, TreeSet → ConcurrentSkipListMap, ConcurrentSkipListSet: sorted keys, O(log n), ranges and atomic pollFirstEntry()/pollLastEntry(); size() is O(n).
  • ArrayList with rare changes and frequent iteration → CopyOnWriteArrayList; with frequent writes → Collections.synchronizedList.
  • A queue where the consumer waits for data (Producer-Consumer) → ArrayBlockingQueue or LinkedBlockingQueue with an explicit capacity.
  • A queue without waiting → ConcurrentLinkedQueue/ConcurrentLinkedDeque: non-blocking, CAS-based, poll() returns null immediately.
  • PriorityQueue → PriorityBlockingQueue.
  • Data that does not change after creation → List.of, Map.of, List.copyOf: readable from any thread without synchronization.

Keep Vector and Hashtable for legacy code only. And remember: a thread-safe collection protects only itself - mutable objects stored in it need their own protection.

Page 1 of 1