Quick revision
The short answer
Iterating a ConcurrentHashMap is weakly consistent: each entry is seen at most once, but each value is read at a different moment, so a transfer that debits an account the iterator already passed and credits one it has not reached yet is counted twice, or not at all in the other direction. If finance needs an exact total, the reader needs a consistent snapshot, from a lock shared by transfers and the report, from an immutable state swapped atomically, or from the database inside a transaction; otherwise document the total as approximate.
What to remember
In this answer, we saw that iterating a ConcurrentHashMap gives each entry at most once but reads every value at a different moment, so a transfer caught mid-report is counted twice or not at all. Exact totals need a consistent snapshot: a read-write lock where transfers share and the report excludes, immutable versions published atomically, or a sum computed in the database inside one transaction. When an approximate number is acceptable, the fast weakly consistent sum is fine, but its name and documentation must say so.
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.
Iterating a ConcurrentHashMap is weakly consistent: each entry is seen at most once, but each value is read at a different moment, so a transfer that debits an account the iterator already passed and credits one it has not reached yet is counted twice, or not at all in the other direction. If finance needs an exact total, the reader needs a consistent snapshot, from a lock shared by transfers and the report, from an immutable state swapped atomically, or from the database inside a transaction; otherwise document the total as approximate.
Why this question is asked
This is a scenario where nothing throws, no test fails, and the numbers are still wrong, which is the most expensive kind of bug in a financial system. Interviewers ask it to see whether we know exactly what ConcurrentHashMap promises during iteration and whether we can choose a consistency mechanism that fits the size of the data and the write load. In this answer, we will reproduce how the total drifts, explain what weakly consistent iteration guarantees, and go through three fixes and their costs, ending with when an approximate total is acceptable.
1Reproducing the Drifting Total
A transfer moves money from one account to another in two map updates. Each update is atomic on its own, but the pair is not. The report walks the 2 million entries and adds up the balances, which takes tens of milliseconds, while transfers keep happening.
5 messages in order. Play them, or step through them one at a time.
Each read was correct when it happened. The reads happened at different moments.
Suppose the iterator has already passed account A, reading its old balance of 1,000, and has not yet reached account Z. A transfer of 250 from A to Z now runs. A's new balance is never read, but Z's new, higher balance is. The report counts the 250 twice. If the transfer goes the other way, from an account not yet reached to one already passed, the 250 is counted nowhere.
2What Weakly Consistent Really Promises
ConcurrentHashMap's Javadoc says its iterators are weakly consistent: they never throw ConcurrentModificationException, they traverse each element at most once, and they reflect the state of the map at some point at or since their creation. The phrase at most once is about keys: no account appears twice, so we cannot double count by revisiting an entry. But each value is read when the iterator reaches it, so the values come from many different moments.
So the sum is a sum of values from 2 million slightly different points in time. The map did nothing wrong: it promised fast, non-blocking iteration and kept that promise. What it never promised was a point-in-time snapshot, and a total that must balance requires one.
3Fix 1: One Lock for Transfers and the Report
The simplest exact fix is a read-write lock. Each transfer takes the read lock, so transfers still run in parallel with each other, and the report takes the write lock, so while it sums, no transfer can be halfway done.
Using the lock in the reversed sense looks odd, but it is correct: what must be exclusive is the report, and what can be shared is the transfers. The cost is that all transfers pause for as long as the sum takes, which for 2 million entries is roughly 10 to 50 ms. Once a minute that is usually fine; ten times a second it is not.
4Fix 2: Immutable State Swapped Atomically
When pauses are unacceptable, we can change how the state is stored. Writers build a new version of the state and publish it through a single atomic reference, and readers take whatever version is current and read it without any lock. Because a version never changes after it is published, a reader always sees a consistent state, both sides of every transfer or neither.
With 2 million accounts we cannot copy everything on each transfer. A persistent map from a library, which shares most of its structure between versions, makes each new version cheap. Another common shape is to serialise all transfers through a single writer thread that applies them in batches and publishes a new snapshot every 100 ms, which suits event-sourced ledgers. Both are bigger changes than a lock, so they are worth it only when transfer throughput is high and reports are frequent.
5Fix 3: Let the Database Do It
If the balances are also persisted, and for money they should be, the cleanest answer is often to compute the total where the data of record lives. A query such as SELECT sum(balance) FROM accounts reads from one snapshot in PostgreSQL even at the default READ COMMITTED level, because a single statement sees one snapshot. If the report reads several tables or runs several statements, running them in one REPEATABLE READ transaction gives them all the same snapshot.
Provided each transfer updates both accounts in one database transaction, the database total is exact and never pauses writers, since readers do not block writers under MVCC. The in-memory map then becomes a cache, and the report is not built on a cache.
6When an Approximate Total Is Acceptable
Not every number needs to balance to the cent. A dashboard showing total deposits rounded to millions, or an alert that fires when the total moves by more than 5 percent, is perfectly served by the weakly consistent sum, which is fast and never blocks. The bug in this scenario is not that the sum is approximate; it is that finance treated an approximate number as exact.
So whichever path we take, the method name and its Javadoc should say what it returns: exactTotal() for the locked or snapshot version, approximateTotal() for the walk over the live map, with a note that it may be off by the transfers in flight.
7Follow-up questions
Would computing the total with balances.reduceValues help?
No. ConcurrentHashMap's bulk operations such as reduceValues and the parallel forms use the same weakly consistent traversal. They can be faster, but the result is still not a point-in-time total.
Can we keep a running total in an AtomicLong instead?
A transfer does not change the true total, so a running total would only change on deposits and withdrawals, and it would be exact if every such change updated it. But that only answers the grand total; any report that needs per-account or per-branch sums still has to read the map, so we still need a snapshot.
Is ReadWriteLock fair to the report?
With the default non-fair mode, a steady stream of readers, here transfers, can delay the writer for a long time. Constructing it with new ReentrantReadWriteLock(true) makes it fair, so the report gets its turn, at a small cost in throughput.
8Conclusion
In this answer, we saw that iterating a ConcurrentHashMap gives each entry at most once but reads every value at a different moment, so a transfer caught mid-report is counted twice or not at all. Exact totals need a consistent snapshot: a read-write lock where transfers share and the report excludes, immutable versions published atomically, or a sum computed in the database inside one transaction. When an approximate number is acceptable, the fast weakly consistent sum is fine, but its name and documentation must say so.
Open with
The totals don't match because ConcurrentHashMap's iteration is weakly consistent. It never throws and each account is visited at most once, but each balance is read at the moment the iterator reaches it, so the sum mixes values from millions of different moments.
Then, if they want more
A transfer is two updates: debit one account, credit another. If the iterator has already passed the debited account and hasn't reached the credited one, the amount is counted twice; the other way round, it isn't counted at all. Each map operation is atomic, but the transfer as a pair isn't, and the report has no point-in-time view.
To fix it, I'd first ask whether finance needs an exact figure. If it does, I need a consistent snapshot.
The simplest is a ReentrantReadWriteLock where transfers take the read lock, so they still run in parallel, and the report takes the write lock, so it sums while no transfer is half done; the cost is pausing transfers for the tens of milliseconds the sum takes.
If that pause is too much, I'd move to immutable versions of the state published through an atomic reference, or a single writer applying transfers in batches. But for money I'd rather compute the total in the database, where each transfer is one transaction and a single SUM query reads one snapshot without blocking writers.
And if an approximate total is fine for some uses, like a dashboard, I'd keep the fast sum but name it approximateTotal and document it.
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 reporting endpoint iterates a ConcurrentHashMap of 2 million account balances to...": https://scrivio-interview-library.netlify.app/java/iteration/705af62f7b/