Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A service uses ConcurrentLinkedQueue and calls queue.size() in a metrics gauge every second; under load CPU rises. It also checks if (!queue.isEmpty()) queue.remove() in several threads and sometimes gets NoSuchElementException. Explain both and fix them.

ConcurrentLinkedQueue has no element counter, so size() walks the whole linked list every time, which is O(n) and only a rough snapshot under concurrent changes; a gauge calling it every second on a long queue burns CPU. The NoSuchElementException comes from a check-then-act race: another thread takes the last element between isEmpty() and remove(). Keep a separate counter or use a queue with an O(1) size, and replace the pair with a single poll() that is checked for null.

Why this question is asked

Concurrent collections make each single method safe, and that leads many of us to assume that any code using them is safe. This question has two bugs that come from the same misunderstanding: one about what a method costs, and one about combining two safe methods. Interviewers ask it to see whether we read the Javadoc of the classes we use and whether we recognise check-then-act. In this answer, we will look at how ConcurrentLinkedQueue is built, see why size() is expensive, reproduce the race, fix both problems, and talk about when to use a blocking queue instead.

1A Quick Recap of ConcurrentLinkedQueue

ConcurrentLinkedQueue is an unbounded, non-blocking, thread-safe FIFO queue. It is a singly linked list of nodes with a head and a tail pointer, and threads update those pointers with compare-and-set (CAS), an atomic CPU instruction that changes a value only if it still holds what we expect. No thread ever takes a lock, so producers and consumers never block each other.

The price of being lock-free is that the queue does not keep a count of its elements. Keeping an exact count would mean updating a shared counter on every offer and poll, and that single counter would become the point where all threads collide, which is what the design avoids.

2Why size() Gets Expensive Under Load

Without a stored count, size() has to walk from the head to the tail and count the live nodes. The Javadoc warns about this: unlike most collections, size is not a constant-time operation, and its result may be inaccurate if elements are added or removed during the walk.

Java
ConcurrentLinkedQueue<Event> queue = new ConcurrentLinkedQueue<>();
// gauge registered with Micrometer, read every second
Gauge.builder("events.queued", queue, ConcurrentLinkedQueue::size).register(registry);
// with 10 elements: about 10 node visits per read
// with 2,000,000 elements: about 2,000,000 node visits per read
// while producers add: the number returned was never exactly true at any moment

So the cost grows with the very thing the gauge is meant to watch. When the system is under load the queue is long, each size() call walks millions of nodes, and it also pulls all those nodes through the CPU caches, slowing the producers and consumers. And the answer is only a snapshot: by the time we read it, it has changed. isEmpty() is different, by the way. It only needs to find the first live node, so it is cheap.

3Fixing the Gauge

We have two good fixes. The first keeps the queue and counts separately. A LongAdder is a counter designed for many writers, which spreads updates across internal cells, so it adds little contention. The trade-off is that the count and the queue are updated in two steps, so the gauge may be off by a few elements for a moment, which is fine for monitoring.

Java
ConcurrentLinkedQueue<Event> queue = new ConcurrentLinkedQueue<>();
LongAdder queued = new LongAdder();
void publish(Event e) { queue.offer(e); queued.increment(); }
Event next() {
Event e = queue.poll();
if (e != null) queued.decrement();
return e;
}
Gauge.builder("events.queued", queued, LongAdder::sum).register(registry); // O(1) per read

The second fix is to choose a queue that already keeps a count. LinkedBlockingQueue stores its size in an AtomicInteger, so size() is a single read, and ArrayBlockingQueue keeps a count field under its lock. Both are also bounded if we give them a capacity, which a queue growing to two million elements probably needs anyway.

4Reproducing the Check-Then-Act Race

Now the second bug. Each thread checks that the queue is not empty and then removes the head. isEmpty() is thread-safe and remove() is thread-safe, but nothing makes the two calls happen together. Between them, another thread is free to run.

Java
// runs in several threads
if (!queue.isEmpty()) { // thread A: false, one element left
// thread B: also false, same element
Event e = queue.remove(); // thread B removes it first
// thread A: NoSuchElementException
handle(e);
}
Step throughTwo threads race for the last element
Thread AQueue (1 element)Thread B
isEmpty()
false
isEmpty()
false
remove()
the last event, queue now empty
remove()
NoSuchElementException

8 messages in order. Play them, or step through them one at a time.

Both checks were true when they ran. Only one element existed to act on.

This pattern is called check-then-act: we check a condition, then act on it, assuming it still holds. In concurrent code the condition can change in between, and with one element left and two threads, it happens regularly under load.

5Fixing the Race With One Atomic Call

The fix is to ask the queue to do the check and the action in one operation. poll() takes the head if there is one and returns null if there is none, atomically. Whatever other threads do, each element is returned to exactly one caller.

Java
Event e = queue.poll(); // atomic: take the head or get null
if (e != null) {
handle(e);
}
// thread A: gets the event thread B: gets null and does nothing

This is a general rule for concurrent collections: use the compound methods they provide, such as poll() on queues or putIfAbsent() and computeIfAbsent() on ConcurrentHashMap, instead of combining a check and an action ourselves. The same rule explains why size() should never drive control decisions, such as if (queue.size() < 1000) queue.offer(e). The size is stale by the time we use it, so the limit is not really enforced. If we need a limit, a bounded LinkedBlockingQueue with offer() enforces it atomically.

6Follow-up questions

Is LinkedBlockingQueue slower than ConcurrentLinkedQueue?

Under very high contention ConcurrentLinkedQueue can be faster because it never locks, but LinkedBlockingQueue uses two separate locks, one for the head and one for the tail, so producers and consumers do not block each other. For most services the difference is small, and the cheap size(), the capacity limit and the blocking take() are worth more.

Why not wrap isEmpty() and remove() in a synchronized block?

That only works if every thread that touches the queue uses the same lock, and then we have turned a lock-free queue into a locked one and given up its only advantage. poll() gives the same correctness without any lock.

Is a LongAdder exact?

sum() is exact when there are no concurrent updates. While threads are updating it, sum() returns a value that may miss updates in progress, which is fine for a gauge. If we need an exact value at a precise moment, no concurrent counter can give it without stopping the writers.

7Conclusion

In this answer, we saw that ConcurrentLinkedQueue does not store its size, so size() walks the whole list, costs O(n) and returns only a snapshot; a gauge reading it every second on a long queue wastes CPU exactly when the system is busiest. We fixed it with a separate LongAdder or a LinkedBlockingQueue or ArrayBlockingQueue, whose size() is cheap. The NoSuchElementException was a check-then-act race between isEmpty() and remove(), fixed by a single atomic poll() checked for null, and we saw why size should not drive control decisions in concurrent code.

What to say in the interviewAbout 90 seconds aloud

Open with

There are two separate problems. First, ConcurrentLinkedQueue is a lock-free linked list and doesn't keep a count, because a shared counter would be a contention point. So size walks the list from head to tail, which is O(n), and the Javadoc warns it is not constant time and may be inaccurate while others modify the queue.

Then, if they want more

Under load the queue is long, so a gauge calling size every second walks millions of nodes exactly when the CPU is busiest.

I would fix that with a LongAdder that I increment on offer and decrement on a successful poll, and point the gauge at that; or, if I also need a capacity limit, switch to LinkedBlockingQueue, which keeps an AtomicInteger count, or ArrayBlockingQueue. Second, isEmpty followed by remove is a check-then-act race.

Each call is thread-safe, but between them another thread can take the last element, so remove throws NoSuchElementException. The fix is to use a single atomic operation: poll, and handle a null result.

More generally, I avoid using size for control decisions in concurrent code, like only offering when size is below a limit, because the value is stale by the time I act on it. If I need a limit, I use a bounded blocking queue and its offer method, which enforces it atomically.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A service uses ConcurrentLinkedQueue and calls queue.size() in a metrics gauge every...": https://scrivio-interview-library.netlify.app/java/queues-and-deques/5504a93eae/