Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

Several services share a mutable in-memory product catalogue that background threads refresh, and you have seen torn reads and ConcurrentModificationException in production. Across the teams that own these services, how would you redesign catalogue handling?

I would replace the shared mutable catalogue with immutable snapshots: each refresh builds a complete new catalogue version from records held in Map.copyOf and List.copyOf, and publishes it atomically through a volatile field or an AtomicReference. Each request reads the reference once and uses that one version throughout, so it never sees a mix of old and new data and nothing can throw ConcurrentModificationException. I would ship the pattern as a small shared library so teams stop writing their own locking, and measure the memory needed to hold two versions during a swap.

Why this question is asked

In-memory reference data such as a product catalogue is read thousands of times per second and refreshed every few minutes, and mutable designs that seemed fine at low traffic start failing as load grows. The symptoms in the question, torn reads where a request sees a price from one refresh and a description from another, and ConcurrentModificationException while iterating, are both signs that readers and writers share mutable structures. Interviewers ask this scenario to see whether we can fix the root cause across several teams, not just patch one service. In this answer, we will see why the current design fails, build the snapshot design step by step, look at how readers should use it, package it for all teams, and plan for memory.

1Why the Current Design Fails

Today a background thread updates the catalogue in place: it clears and refills maps, or changes fields of existing product objects one by one, while request threads read the same structures. Two different failures follow from this. A HashMap or ArrayList that is changed while another thread iterates it detects the change and throws ConcurrentModificationException, or, worse, silently returns wrong results, since these classes are not thread-safe at all. And a request that reads several values, such as a product's price and then its currency or discount, can read some of them before the refresh touches them and some after, a torn read that produces a combination that never existed.

Java
// Background refresh, today
catalogue.products.clear(); // readers now see an empty catalogue
for (ProductRow r : rows) catalogue.products.put(r.id(), toProduct(r));
// Request thread at the same time
for (Product p : catalogue.products.values()) { ... } // ConcurrentModificationException
Product p = catalogue.products.get(id);
BigDecimal price = p.price; // new price
String currency = p.currency; // old currency: a torn read

Adding locks around every read would fix correctness but make every request contend on the same lock, and each team has already tried its own variant. The better fix is to stop changing shared data at all.

2Build Each Version as an Immutable Snapshot

A snapshot is a complete, immutable catalogue version. Products become records whose fields are immutable types, collections inside are copied with List.copyOf or Map.copyOf, and the catalogue itself is a record holding the maps. The refresh thread builds the whole new version privately, where no reader can see it, and only then makes it visible.

Java
record Product(String id, String name, Money price, List<String> categories) {
Product { categories = List.copyOf(categories); }
}
record Catalogue(long version, Instant loadedAt, Map<String, Product> byId) {
Catalogue { byId = Map.copyOf(byId); }
Optional<Product> find(String id) { return Optional.ofNullable(byId.get(id)); }
}
Catalogue build(List<ProductRow> rows, long version) {
Map<String, Product> m = new HashMap<>();
for (ProductRow r : rows) m.put(r.id(), toProduct(r)); // private to the refresh thread
return new Catalogue(version, Instant.now(), m); // frozen from here on
}

Notice that the HashMap is only ever touched by the refresh thread, before it is copied. After the copy, nothing can change any part of the catalogue, so readers need no locks and cannot cause or suffer a ConcurrentModificationException.

3Publish the New Version Atomically

To make a new version visible, the refresh replaces one reference. An AtomicReference, or a volatile field, gives two guarantees we need: the replacement is a single atomic step, so readers see either the old catalogue or the new one, never a half-way state, and a reader that sees the new reference is guaranteed to see the fully built catalogue behind it, because a volatile write happens-before the reads that see it.

Java
private final AtomicReference<Catalogue> current = new AtomicReference<>(Catalogue.empty());
void refresh() {
Catalogue next = build(loadRows(), current.get().version() + 1);
current.set(next); // one atomic switch; the old version becomes garbage later
}
Catalogue snapshot() { return current.get(); }
Step throughRefresh while requests are in flight
Request 1Current refRefresh threadRequest 2
get() -> version 7
build version 8 privately
set(version 8)
keeps using version 7 to the end
get() -> version 8
uses version 8 throughout

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

Each request works on one version from start to finish; the switch never disturbs a request in progress.

4Read the Reference Once per Request

The snapshot design only prevents torn reads if each request reads the reference once and uses that object for the whole request. If code calls snapshot() several times, it can get version 7 for the first lookup and version 8 for the second, which is a torn read at a larger scale.

Java
// Wrong: two reads of the reference can see two versions
Money price = catalog.snapshot().find(id).orElseThrow().price();
String name = catalog.snapshot().find(id).orElseThrow().name();
// Right: one read per request
Catalogue c = catalog.snapshot();
Product p = c.find(id).orElseThrow();
Money price2 = p.price(); // both values from the same version
String name2 = p.name();

A useful habit is to pass the Catalogue object down the call chain rather than the holder, so every component in a request uses the same version. Logging c.version() with each request also makes it easy to tell which data a response was based on.

5Ship It as a Shared Library

Several services have this problem, and each team has written its own mix of synchronized blocks, ConcurrentHashMaps and flags. I would extract the pattern into a small library with a holder type, for example SnapshotHolder<T>, that offers get() and refresh(Supplier<T>), handles scheduling, keeps the last good version if a load fails, and exposes metrics such as the current version, the age of the snapshot and the duration of the last load.

The library makes the safe path the easy one. Teams provide only the loading function and the immutable record types, and code review can check that catalogue types are records with copied collections. The library also gives one place to add features later, such as a refresh triggered by an event instead of a timer.

Step throughShared snapshot library
  1. Service codeCatalogue c = holder.get(); use c for the whole request
  2. SnapshotHolder<T>AtomicReference, scheduling, keep last good version
  3. Loader supplied by each teamreads the database or feed, builds records
  4. Immutable recordsMap.copyOf and List.copyOf inside
  5. Metricsversion, snapshot age, load time and failures

5 layers, from the top down. Step through them one at a time.

6Plan for Two Versions in Memory

During a swap, the old version is still in use by requests that started before it, while the new version has already been built. So memory must fit two full catalogues at once, plus the temporary HashMap used while building. If a catalogue takes 400 MB of heap, the peak is around 800 MB or more, and the old version becomes garbage only after the last request using it finishes.

We should measure this rather than guess: take a heap histogram or a JFR recording around a refresh to see the real size of one version and the peak during a swap, and size the heap with headroom. If two copies do not fit, we can reuse unchanged records between versions, which is safe precisely because they are immutable, so a refresh where 2 percent of products changed shares the other 98 percent. Another option is to split the catalogue into partitions that are refreshed separately.

7Follow-up questions

Why not use ConcurrentHashMap and update entries in place?

ConcurrentHashMap removes ConcurrentModificationException and keeps individual operations safe, but it does not give a consistent view across entries. A request reading 20 products during a refresh could see 10 old and 10 new ones, and a product object changed field by field can still be torn. Snapshots give consistency for the whole request at no locking cost.

What happens if a refresh fails halfway?

Nothing visible, which is one of the best properties of the design. The new version is built privately, so if the load throws, we never call set, and readers keep using the last good version. The library logs the failure, records a metric and retries on the next schedule.

Is AtomicReference needed, or is a volatile field enough?

With a single refresh thread, a volatile field is enough, because there is only one writer. AtomicReference adds compareAndSet and updateAndGet, which matter if several threads might refresh at once and we must not lose an update. In a shared library, AtomicReference is the safer default.

8Conclusion

In this answer, we saw that the torn reads and ConcurrentModificationExceptions come from readers and a refresher sharing mutable structures. The redesign builds each catalogue version as an immutable snapshot of records and copied collections, publishes it with one atomic switch through an AtomicReference or volatile field, and has each request read the reference once so it sees a single consistent version. A shared library gives every team the same safe pattern with metrics and failure handling, and we plan memory for two versions during a swap, sharing unchanged records where needed.

What to say in the interviewAbout 90 seconds aloud

Open with

Both symptoms come from the same cause: request threads read structures that a background thread is changing in place. ConcurrentModificationException is a HashMap or list being changed while someone iterates it, and the torn reads are a request seeing some fields from before a refresh and some from after.

Then, if they want more

I would stop mutating shared data. Each refresh builds a complete new catalogue privately, as records with immutable fields and collections copied with Map.copyOf and List.copyOf, and then publishes it with a single set on an AtomicReference, or a volatile field if there is one writer.

Readers see either the old version or the new one, never a mix, and the volatile semantics guarantee they see the fully built object. The important rule for readers is to call get once per request and pass that catalogue down, so all lookups in a request come from the same version; logging the version number helps debugging.

Because several teams have this problem, I would put it in a shared SnapshotHolder library that does scheduling, keeps the last good version when a load fails and exposes metrics such as snapshot age, so nobody writes their own locking again.

Finally, I would measure memory, since two full versions exist during a swap; if that is too much, unchanged records can be shared between versions because they are immutable.

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 "Several services share a mutable in-memory product catalogue that background threads...": https://scrivio-interview-library.netlify.app/java/immutability/853f0b3e97/