Quick revision
The short answer
Returning the internal ArrayList lets every caller iterate a list that a background thread is changing, which causes the ConcurrentModificationException and, worse, unsynchronized reads that return wrong results. The contract should be that getSubscribers() returns an immutable snapshot, either a fresh List.copyOf made under the library's lock, or, since reads dominate, an immutable list or CopyOnWriteArrayList held in a volatile field and returned directly. Document the thread-safety and iteration semantics, release it with clear notes because callers that mutated the list will now get UnsupportedOperationException, and add a concurrent iteration test.
What to remember
In this answer, we saw that returning the internal ArrayList causes both the intermittent ConcurrentModificationException and silent wrong results, because callers iterate an unsynchronized list a background thread is changing. The contract is that getSubscribers() returns an immutable snapshot, documented in the Javadoc. We can build it with List.copyOf under a lock, or, since reads dominate, with an immutable list or CopyOnWriteArrayList published through a volatile field. We release it with notes about the UnsupportedOperationException that mutating callers will now get, and add a concurrent iteration test.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Returning the internal ArrayList lets every caller iterate a list that a background thread is changing, which causes the ConcurrentModificationException and, worse, unsynchronized reads that return wrong results. The contract should be that getSubscribers() returns an immutable snapshot, either a fresh List.copyOf made under the library's lock, or, since reads dominate, an immutable list or CopyOnWriteArrayList held in a volatile field and returned directly. Document the thread-safety and iteration semantics, release it with clear notes because callers that mutated the list will now get UnsupportedOperationException, and add a concurrent iteration test.
Why this question is asked
Leaking internal state is one of the oldest mistakes in API design, and in a shared library it is multiplied by every service that depends on it. Here the leak is also a data race: thirty services read a list that a background thread writes without any synchronization. Interviewers ask this to see whether we can define a clear contract, pick a data structure that makes the contract cheap to keep, and change a widely used API without breaking its users. In this answer, we will see why the current code fails in two different ways, define the contract, look at two implementations, plan the release and add the test that keeps it fixed.
1Why the Current Code Fails in Two Ways
The library's background thread adds and removes subscribers in its internal ArrayList, and getSubscribers() returns that same object. So callers in thirty services iterate the very list that is being changed. When the background thread changes it during a caller's loop, the caller's fail-fast iterator may notice through modCount and throw ConcurrentModificationException. That is the intermittent exception.
The occasional wrong results are the more serious failure. ArrayList is not thread-safe, and nothing makes the background thread's writes visible to the callers' threads in a defined order. A caller can see the new size but the old array, read a null slot, miss a subscriber or see one twice. The fail-fast check is best-effort and does not catch these cases. And because the list is mutable, some callers may even be changing the library's internal state themselves.
2The Contract to Define
The rule to adopt is that a library never exposes its internal mutable collections. The returned list must be one of two things, and the Javadoc must say which. An unmodifiable snapshot is a list that reflects the subscribers at one moment and never changes afterwards, so callers can iterate it, keep it and pass it to other threads safely. A read-only view reflects later changes, which is rarely what a caller wants and still needs a thread-safe backing collection, so for this case the snapshot is the right contract.
We write the contract down: the returned list is an immutable snapshot taken at the time of the call; it is safe to iterate from any thread; it does not reflect later subscriptions; attempts to modify it throw UnsupportedOperationException; to change subscriptions, use subscribe() and unsubscribe(). Writing it down turns an accident of implementation into a promise the library team must keep.
3Implementation 1: Copy Under a Lock
The smallest change keeps the ArrayList, guards every access with the same lock, and returns a copy.
Notice that the copy is made inside the lock, so it captures a consistent state. List.copyOf returns an unmodifiable list and rejects null elements, which is a useful check here. The cost is one array copy per call. With 200 subscribers and a few thousand calls a second, that is negligible; with 100,000 subscribers and very frequent calls, it starts to matter.
4Implementation 2: Publish an Immutable List
The question says the background thread updates the list, and callers read it from thirty services, so reads far outnumber writes. In that case we can move the copying to the write side. The writer builds a new immutable list on each change and publishes it through a volatile field; readers just return the current reference, with no lock and no copy.
| Approach | Read cost | Write cost | Caller sees |
|---|---|---|---|
Return internal ArrayList (today) | Free | Free | A racing, mutable list |
List.copyOf under a lock | One copy per call | Cheap, under the lock | Immutable snapshot |
| Immutable list in a volatile field | Free | One copy per change | Immutable snapshot |
The volatile write guarantees that a reader sees a fully built list, and because that list never changes, every caller iterates a consistent snapshot. CopyOnWriteArrayList does the same thing internally, and returning it wrapped in Collections.unmodifiableList would also work, but then the view reflects later changes, so the explicit immutable list matches our snapshot contract more exactly.
5Releasing the Change Without Surprising Thirty Teams
The change is a behaviour change for any caller that modified the returned list, because those calls now throw UnsupportedOperationException. Some may have relied on it, for example to remove expired subscribers. Before releasing, we search the thirty services for mutating calls on the result, which in a monorepo or with a code search tool takes minutes, and add proper methods such as unsubscribe() or removeIf(predicate) to the library for the cases we find.
Then we ship with release notes that state the new contract and the one breaking case. Whether that is a minor or a major version depends on what the old contract said. If modification was never documented, many teams treat this as a bug fix and ship a minor version with prominent notes; under strict semantic versioning it is a breaking change and gets a major version. Either way, a deprecation-style first step helps: a release that logs a warning when the returned list is modified, followed by the release that forbids it.
6A Test That Keeps It Fixed
Finally we add a test that does what production does: one thread subscribes and unsubscribes in a loop while several threads iterate getSubscribers() and check every element. With the old implementation it fails within a second or two with ConcurrentModificationException or a null element; with the new one it runs clean for thousands of iterations. It is not a proof, because races are probabilistic, but it catches a regression the moment someone returns a live collection again.
7Follow-up questions
Why not return Collections.unmodifiableList(subscribers)?
That stops callers from modifying the list, but it is a view over the same unsynchronized ArrayList. Iterating it while the background thread writes still throws ConcurrentModificationException or reads inconsistent data. Unmodifiable is not the same as immutable or thread-safe.
Should getSubscribers() return a Stream or an Iterable instead?
It could, and a Stream would make the read-only nature obvious. But many callers want size() or index access, and a List snapshot is the least surprising type for thirty teams. The important part is the immutability and the documented semantics, not the type.
What if a caller needs to be notified of changes?
That is a different contract. Add a listener API, such as onSubscribersChanged(Consumer<List<Subscriber>>), that delivers each new snapshot, instead of letting callers poll or hold a live view.
8Conclusion
In this answer, we saw that returning the internal ArrayList causes both the intermittent ConcurrentModificationException and silent wrong results, because callers iterate an unsynchronized list a background thread is changing. The contract is that getSubscribers() returns an immutable snapshot, documented in the Javadoc. We can build it with List.copyOf under a lock, or, since reads dominate, with an immutable list or CopyOnWriteArrayList published through a volatile field. We release it with notes about the UnsupportedOperationException that mutating callers will now get, and add a concurrent iteration test.
Open with
The root problem is that the library hands out its internal ArrayList while its own background thread changes it. Callers' iterators sometimes detect that and throw ConcurrentModificationException, but the bigger problem is the wrong results: ArrayList isn't thread-safe, so readers can see a stale array, a null slot or a missed subscriber, and the fail-fast check doesn't catch that.
Then, if they want more
Some callers might even be modifying the library's state. So the contract I'd define is: getSubscribers returns an immutable snapshot taken at the time of the call, safe to iterate from any thread, not reflecting later changes, and modifying it throws UnsupportedOperationException. I'd put that in the Javadoc.
For the implementation, since reads dominate, I'd keep the subscribers as an immutable list in a volatile field: writers build a new list under a lock and publish it with one volatile write, and readers just return the reference, with no lock and no copy. A CopyOnWriteArrayList gives the same trade-off.
If writes were frequent, I'd instead copy with List.copyOf under the same lock the writer uses. For the rollout, I'd first search the thirty services for code that mutates the returned list and add proper methods like unsubscribe for those cases.
Then I'd release with clear notes; strictly that's a breaking change, so if mutation was ever implied, it goes in a major version, otherwise a minor one with a warning release first. And I'd add a stress test that iterates while another thread subscribes and unsubscribes.
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.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
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 shared library used by 30 services exposes getSubscribers() returning its internal...": https://scrivio-interview-library.netlify.app/java/iteration/adb014b043/