Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A breadth-first traversal over a graph with millions of nodes uses LinkedList as the queue and shows heavy GC. Would you switch to ArrayDeque, and what else would you consider?

Yes, switching to ArrayDeque removes the node object LinkedList allocates for every enqueued element and keeps the frontier in one contiguous array, which cuts GC work and cache misses. I would also pre-size it if the frontier size is roughly known, replace a HashSet<Integer> visited set with a BitSet when node ids are dense integers, consider a primitive int queue to avoid boxing entirely, and measure allocation rate with JFR before and after.

Why this question is asked

Breadth-first search is a simple algorithm that becomes a memory problem at scale. With millions of nodes, every enqueue and every visited check can allocate objects, and the garbage collector ends up doing more work than the traversal itself. Interviewers ask this as a scenario because the obvious answer, switching the queue class, is right but incomplete: the visited set and boxing often cost more than the queue. In this answer, we will recap BFS and count what the current code allocates, switch to ArrayDeque and see why it helps, fix the visited set and boxing, write a fully primitive version, and measure the result with JFR.

1A Quick Recap of BFS and What It Allocates

Breadth-first search visits a graph level by level. It puts the start node in a queue, then repeatedly takes the node at the head, looks at its neighbours, and adds every neighbour not yet visited to the tail. A visited set makes sure each node is enqueued once. The queue holds the frontier, the nodes discovered but not yet processed.

Java
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
queue.add(start); visited.add(start);
while (!queue.isEmpty()) {
int node = queue.poll();
for (int next : graph.neighbours(node)) {
if (visited.add(next)) queue.add(next); // each add boxes next and creates a node
}
}

Now count objects for a graph of 10 million nodes. Each enqueue boxes the int into an Integer (16 bytes; only -128 to 127 are cached) and creates a LinkedList node (about 24 bytes). Each visited.add creates a HashMap node (about 32 bytes) and may reuse the same Integer. That is roughly 70 bytes of new objects per node, about 700 MB over one traversal, and the visited set's 300 MB or more stays alive until the end, so it is promoted to the old generation and makes collections slower. The GC log is telling the truth: this code allocates for nearly every step.

2Why ArrayDeque Helps

ArrayDeque stores references in a circular array. Enqueuing writes one slot; dequeuing clears one. There is no node per element, so the 24 bytes per enqueue and the garbage they become disappear. The elements also sit next to each other in memory, so polling walks forward through the array instead of chasing pointers scattered through the heap, which means far fewer cache misses.

The array only grows when the frontier is larger than its capacity, and growth is amortized. If we know roughly how wide the frontier gets, for example from previous runs, we can pre-size it with new ArrayDeque<>(2_000_000) and avoid the repeated copy steps. The change is a one-line swap, and it is safe because the code only uses queue methods.

Java
Queue<Integer> queue = new ArrayDeque<>(expectedFrontier); // was: new LinkedList<>()

But notice what remains: every element is still a boxed Integer, and the visited set is still a HashSet with a node per entry. Switching the queue alone typically removes a third of the allocation, not all of it.

3Fixing the Visited Set

When node ids are dense integers from 0 to n - 1, which is common when graphs are loaded into arrays, the visited set can be a BitSet: one bit per node, 10 million bits, about 1.25 MB, allocated once. Checking and setting a bit is a shift and a mask, with no allocation at all. Compared with a HashSet<Integer> of 10 million entries, which needs several hundred megabytes, that is a reduction of more than two hundred times.

If ids are not dense, for example 64-bit ids from a database, we can map them to dense indexes once when loading the graph, or use a primitive hash set from a library such as fastutil or Eclipse Collections, which stores longs in an array without boxing or node objects.

Java
BitSet visited = new BitSet(n); // n = 10,000,000 -> about 1.25 MB
visited.set(start);
// ...
if (!visited.get(next)) { visited.set(next); queue.add(next); }

4Going Fully Primitive

Once visited is a BitSet, the remaining allocation is the boxing of each node id into an Integer for the queue. A primitive int queue removes it. For BFS there is a neat simplification: every node is enqueued at most once, so a plain int array of size n with a read index and a write index is enough, with no wrap-around needed.

Java
int[] queue = new int[n]; // each node enters at most once, 40 MB for 10M nodes
int head = 0, tail = 0;
BitSet visited = new BitSet(n);
queue[tail++] = start; visited.set(start);
while (head < tail) {
int node = queue[head++];
for (int i = graph.offset[node]; i < graph.offset[node + 1]; i++) { // CSR adjacency arrays
int next = graph.targets[i];
if (!visited.get(next)) { visited.set(next); queue[tail++] = next; }
}
}
// allocations inside the loop: none
Per-node cost of each version, 10 million nodes
VersionAllocated per nodeVisited set size
LinkedList + HashSet<Integer>about 70 bytes300 MB or more, live
ArrayDeque + HashSet<Integer>about 50 bytes300 MB or more, live
ArrayDeque + BitSetabout 16 bytes (Integer box)1.25 MB
int[] queue + BitSet0 bytes1.25 MB
Rough estimates for planning; measure with JFR on the real graph.

Notice that the adjacency is also stored as two int arrays, a compressed sparse row layout where offset[node] marks where a node's neighbours start in targets. If graph.neighbours(node) returned a new List<Integer> per call, it would allocate even more than the queue did, so it is worth checking that part of the code too. If the frontier is much smaller than n and memory is tight, a growable primitive ring buffer, such as fastutil's IntArrayFIFOQueue, is the alternative.

5Measuring Before and After With JFR

Before changing anything, we record what the program allocates. Java Flight Recorder is built into the JDK and cheap enough to run on a production-like workload. We start the job with a recording, then look at allocation by class and by stack trace.

Shell
java -XX:StartFlightRecording=duration=120s,filename=bfs-before.jfr -jar traversal.jar
jfr summary bfs-before.jfr # event counts
jfr print --events jdk.ObjectAllocationSample bfs-before.jfr # what is allocated, and where
jfr print --events jdk.GarbageCollection bfs-before.jfr # pause times

JDK Mission Control shows the same data graphically, with top allocating classes such as LinkedList$Node, Integer and HashMap$Node and the stack traces that created them. After each change, we record again with the same input and compare allocation rate, GC count and pause times, and total run time. That tells us which change mattered, and it protects us from optimizing the queue while the real cost was in neighbours() returning boxed lists.

6Follow-up questions

Would increasing the heap or changing the collector be enough?

It may reduce pauses, but it treats the symptom. The program would still create hundreds of megabytes of garbage per traversal and keep a huge visited set alive. Removing the allocation is usually cheaper and more reliable than tuning the collector around it.

Does the order of BFS change with ArrayDeque or an int array?

No. All three are first-in-first-out queues, so nodes are processed in the same order and the result, such as distances or the BFS tree, is identical. Only the memory layout changes.

When would you not go fully primitive?

When the graph is small, the code is not on a hot path, or readability matters more than the last 10 percent. ArrayDeque plus BitSet already removes most of the cost while keeping ordinary Java collections. The int array version is worth it for very large graphs or traversals run many times per second.

7Conclusion

In this answer, we saw that a LinkedList queue allocates a node per enqueued element, which together with boxed Integers and a HashSet visited set creates heavy GC pressure on a graph of millions of nodes. Switching to a pre-sized ArrayDeque removes the nodes and improves locality, a BitSet makes the visited set tiny and allocation-free when ids are dense, and a primitive int array queue removes boxing entirely. We measured allocation with JFR before and after to confirm which change mattered.

What to say in the interviewAbout 100 seconds aloud

Open with

Yes, I would switch to ArrayDeque, but I would not stop there. LinkedList allocates a node object of about 24 bytes for every element I enqueue, and those nodes become garbage right after poll, so with millions of nodes that is a constant stream of allocation, and walking scattered nodes causes cache misses.

Then, if they want more

ArrayDeque keeps references in a contiguous circular array, so there is no per-element object, and if I know roughly how large the frontier gets I can pre-size it to avoid repeated growth. But in typical BFS code the queue is only part of the allocation.

The visited set is often a HashSet of Integer, which costs a node of about 32 bytes per entry plus the boxed Integer, and it stays alive for the whole traversal. If node ids are dense integers, I would replace it with a BitSet, which is about 1.25 megabytes for ten million nodes and never allocates.

Then the remaining cost is boxing each id into an Integer for the queue, so for really large graphs I would use a primitive int queue. In BFS each node is enqueued at most once, so a plain int array of size n with head and tail indexes is enough.

I would also check that the neighbour lookup does not return boxed lists. And before and after each change, I would record with Java Flight Recorder, look at allocation samples and GC events, and compare allocation rate, pause times and run time, so I know which change actually helped.

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 breadth-first traversal over a graph with millions of nodes uses LinkedList as the...": https://scrivio-interview-library.netlify.app/java/queues-and-deques/ecc3bd6a8d/