Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

In production a scheduled job that iterates a shared ArrayList occasionally fails with ConcurrentModificationException while request threads add to the list. A teammate proposes catching the exception and retrying. What do you say?

Catching the exception and retrying treats the symptom of a data race. ConcurrentModificationException is only a best-effort signal that the job iterated an ArrayList while request threads changed it without synchronization, and its absence does not mean the code worked: concurrent add() on an ArrayList can lose elements, leave null slots or corrupt the size, which no retry repairs. Fix the sharing instead, with a CopyOnWriteArrayList if writes are rare, a ConcurrentLinkedQueue, a lock around both adds and iteration, or an atomic swap of the list, and add a stress test that reproduces the race.

Why this question is asked

A teammate proposing to catch and retry is making a reasonable-sounding suggestion: the failure is rare and the retry usually succeeds. Interviewers use this situation to see whether we can explain, kindly and precisely, why the fix would hide a bug rather than remove it, and whether we know the safe alternatives. In this answer, we will see what the exception is really telling us, what else goes wrong that never throws, compare the fixes, and write a test that proves the problem and the fix.

1What the Exception Is Really Telling Us

ArrayList is not thread-safe. Its methods read and write plain fields, the element array, the size and modCount, with no locking and no memory visibility guarantees between threads. Here, request threads call add() while the scheduled job iterates the list. The job's iterator sometimes notices that modCount changed and throws ConcurrentModificationException.

The Javadoc describes that check as best-effort: it cannot be guaranteed in the presence of unsynchronized concurrent modification. So the exception is a sample of a race, caught by luck on some runs. On the other runs the same race happened and nothing noticed. Retrying only makes it more likely that the job finishes a run in which the race went undetected.

2Damage That No Retry Can Repair

The race does more than confuse the job's iterator. Two request threads calling add() at the same time can both read the same size, both write their element into the same slot, and both set size to the same new value. One element is lost. If one add triggers a resize while the other writes into the old array, the write can land in an array that is about to be discarded. And another thread can see the new size before it sees the element, reading null.

Java
List<String> events = new ArrayList<>(); // shared, unsynchronized
ExecutorService pool = Executors.newFixedThreadPool(8);
for (int i = 0; i < 100_000; i++) {
int n = i;
pool.submit(() -> events.add("e" + n));
}
pool.shutdown(); pool.awaitTermination(10, TimeUnit.SECONDS);
System.out.println(events.size()); // e.g. 99,312, not 100,000
// some runs also throw ArrayIndexOutOfBoundsException inside add(), and some slots are null
What the race can do, and what a retry fixes
Effect of the raceVisible?Fixed by retry?
Iterator detects modCount changeYes: CMEHides it for that run
Two adds write the same slotNoNo: element lost
Size updated before the elementSometimes: nullNo
Add during a resizeSometimes: AIOOBENo: element lost
Job reads stale size or arrayNoNo: items skipped
Only the first row throws. The others are silent.

None of this is visible to the job. If an event was lost by a concurrent add, the retry processes a list that simply does not contain it. If a null slot appears, the job may fail with a NullPointerException later or skip it silently. The retry would turn a loud, occasional failure into silent, occasional data loss, which is far worse.

3Fixing the Sharing

The right fix depends on how the list is used. If writes are rare and the job iterates often, a CopyOnWriteArrayList gives each iteration a snapshot and makes every add safe, at the cost of copying the array on each write; with thousands of adds per second it becomes too expensive. If request threads add many items and the job drains them, the list is really a queue, and a ConcurrentLinkedQueue fits: request threads offer(), the job poll()s until it gets null, and each item is taken exactly once.

If we must keep the list, every access must take the same lock: synchronized (list) around each add and around the job's whole iteration, or a Collections.synchronizedList with manual synchronization during iteration. That is correct but blocks request threads while the job runs. The fourth option, often the best for a batch job, is to swap the list.

Java
private final AtomicReference<List<Event>> pending =
new AtomicReference<>(new CopyOnWriteArrayList<>());
void onRequest(Event e) { pending.get().add(e); } // request threads
@Scheduled(fixedDelay = 60_000)
void flush() {
List<Event> batch = pending.getAndSet(new CopyOnWriteArrayList<>()); // atomic swap
for (Event e : batch) process(e); // later adds go to the new list
}

Notice the catch in a swap: a request thread may have read the old list just before the swap and add to it just after, so that add would be missed by this run. Using a thread-safe list for each batch, as here, keeps the add itself safe, but the late item sits in a list no one will process. A ConcurrentLinkedQueue drained with poll() avoids that window completely, which is why it is usually the simplest correct design for this job.

4A Stress Test That Reproduces the Race

Before fixing, we write a test that fails with the current code, so we know we understood the bug, and passes after the fix. Several threads add as fast as possible while another thread repeatedly runs the job's logic, and at the end we check that every added item was processed exactly once and the count matches. With the ArrayList it fails within seconds, by exception or by count mismatch; with the queue it passes. Tools such as jcstress can explore these interleavings more systematically for library code, but even a simple loop test catches this one.

5Follow-up questions

Is a retry ever right for ConcurrentModificationException?

Practically never. The exception always means code changed a collection during iteration in a way it was not designed for, which is a bug in the program, not a transient condition like a network timeout. The fix is in the code.

Would Vector or Collections.synchronizedList be enough?

They make each single call safe, so add() no longer loses elements. But their iterators are still fail-fast and not synchronized across the loop, so the job must hold the list's lock for the whole iteration, as the Javadoc of synchronizedList requires, or it will still see the exception.

How do we explain this to the teammate without making it personal?

Show the evidence: run the lost-elements snippet and the stress test together, so the team sees that items vanish even when no exception is thrown. It moves the discussion from opinion to a reproducible fact, and the fix becomes the obvious next step.

6Conclusion

In this answer, we saw that ConcurrentModificationException from the job is a best-effort signal of an unsynchronized data race on a shared ArrayList, and that the race also loses elements, writes null slots and corrupts the size without any exception, so catching and retrying would hide a bug while keeping its damage. We fixed the sharing with a CopyOnWriteArrayList, a ConcurrentLinkedQueue drained by the job, a lock around every access, or an atomic swap, and wrote a stress test that fails before the fix and passes after it.

What to say in the interviewAbout 100 seconds aloud

Open with

I'd push back on the retry, because the exception isn't the problem, it's a symptom. ArrayList isn't thread-safe, and the request threads are adding to it while the job iterates with no synchronization.

Then, if they want more

The fail-fast check catches that only on a best-effort basis, so the exception is a lucky sample of a data race. The runs where nothing is thrown are not correct either.

Two concurrent adds can write into the same slot and lose an element, an add during a resize can throw ArrayIndexOutOfBounds or lose the write, and the job can see a size that's ahead of the elements and read nulls.

A retry fixes none of that; it just hides the one visible signal, so we'd go from occasional exceptions to silent data loss. The fix is to make the sharing safe. If the job is really draining items that requests produce, I'd use a ConcurrentLinkedQueue: requests offer, the job polls until null, and each item is processed exactly once.

If writes are rare and it really is a list, CopyOnWriteArrayList works. Otherwise a single lock around both the adds and the job's iteration, accepting that requests block while the job runs. Swapping the list atomically with getAndSet is another option, but there's a small window where a late add goes to the old list, so I'd prefer the queue.

And before changing anything, I'd add a stress test with many writer threads and the job running in a loop that checks every item is processed exactly once, so we see it fail now and pass after the fix.

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 "In production a scheduled job that iterates a shared ArrayList occasionally fails with...": https://scrivio-interview-library.netlify.app/java/iteration/87c90aff9a/