Quick revision
The short answer
The limit leaks because the size() check and the put that follows are two separate operations: under load, dozens of threads can all read 999, all pass the check, and all add a session before any of them sees the new size. size() is also only an estimate while other threads are updating the map. To enforce a hard bound we need one atomic step that both checks and reserves a slot, such as a Semaphore with 1,000 permits acquired with tryAcquire before adding and released in finally or on session expiry, or an AtomicInteger updated with a compare-and-set loop.
What to remember
In this answer, we saw why a limit guarded by activeSessions.size() leaks: the check and the put are separate operations, so many threads pass the check before any of them adds, and size() is only an estimate under concurrent updates anyway, just like mappingCount(). We enforced a hard bound with a Semaphore acquired before adding and with an equivalent AtomicInteger compare-and-set loop, made sure permits are released exactly once in finally blocks or on session expiry, and tested the high-water mark with many concurrent threads.
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.
The limit leaks because the size() check and the put that follows are two separate operations: under load, dozens of threads can all read 999, all pass the check, and all add a session before any of them sees the new size. size() is also only an estimate while other threads are updating the map. To enforce a hard bound we need one atomic step that both checks and reserves a slot, such as a Semaphore with 1,000 permits acquired with tryAcquire before adding and released in finally or on session expiry, or an AtomicInteger updated with a compare-and-set loop.
Why this question is asked
Limits on concurrent work are everywhere in services: maximum open sessions, maximum in-flight requests to a downstream, maximum jobs per tenant. When such a limit leaks, the damage is real: memory runs out, a downstream gets overloaded, or a licence agreement is broken. Interviewers ask this question because the bug is a textbook check-then-act race hidden behind a thread-safe collection, and because the fix needs care about releasing what we reserved. In this answer, we will recap what size() means on a concurrent map, reproduce how 1,050 sessions slip in, enforce the limit with a Semaphore and with an AtomicInteger, make sure permits are never leaked, and test that the bound holds.
1A Quick Recap: What size() Means on a Concurrent Map
On a plain HashMap used by one thread, size() is an exact count. ConcurrentHashMap is different. To avoid a single counter that every writer fights over, it keeps a base count plus an array of counter cells, much like a LongAdder, and size() adds them up at the moment we call it. While other threads are adding and removing, that sum is a moving estimate: by the time the number reaches our code, the real size may already be different.
mappingCount() exists because size() returns an int and a map can, in theory, hold more than Integer.MAX_VALUE entries. It returns a long, but it is computed the same way, so it has the same nature: a good estimate, not a lock-protected exact count. Neither method was designed to be the guard of a hard limit.
2Reproducing the Leak
Here is the shape of the code in the question. The check and the insert are separate lines.
7 messages in order. Play them, or step through them one at a time.
With 60 threads instead of 2, the overshoot reaches the 1,050 seen in production.
Imagine the map holds 999 sessions and 60 request threads arrive within the same millisecond. Each thread calls size() and gets 999, because none of the others has reached its put yet. All 60 pass the check, all 60 put, and the map now holds 1,059 sessions. Nothing in the map is broken; every put worked. The decision each thread made from size() was simply out of date by the time it acted.
Notice that making size() exact would not fix this. Even a perfectly exact count is useless if another thread can change the map between reading the count and adding to it. The check and the reservation must be one atomic step.
3Fix 1: A Semaphore Holds the Permits
A Semaphore is a counter of permits from java.util.concurrent. acquire() takes a permit and waits if none is left; tryAcquire() takes one only if it is available and returns false otherwise. Taking a permit is atomic, so with 1,000 permits at most 1,000 threads can ever hold one at the same time, no matter how they interleave.
The rate limiter now asks the Semaphore, not the map, whether there is room. The map only stores the sessions. Notice that close() releases a permit only when remove() actually removed something. If two threads close the same session, only one of them gets a non-null result, so we never release twice and inflate the limit above 1,000. tryAcquire() without a timeout is the right call for a limiter that should reject immediately; tryAcquire(50, TimeUnit.MILLISECONDS) would let callers wait briefly instead.
4Fix 2: An AtomicInteger With a Compare-and-Set Loop
If we prefer a plain counter, an AtomicInteger works as long as we never increment blindly. We read the current value, decide, and then publish our decision with compareAndSet, which only succeeds if nobody changed the value since we read it. If someone did, we read again and retry.
This is exactly what tryAcquire does inside a Semaphore, so the two fixes are equivalent in strength. The Semaphore is usually clearer because it names the idea, and it can also make callers wait. The loop version is handy when the limit can change at runtime or when the decision depends on more than one number. Java 8 also added active.getAndUpdate(...), but a function that might refuse needs the explicit loop shown here.
5Never Leak a Permit
Every acquired permit must come back exactly once, or the limiter slowly shrinks until it rejects everything. Sessions end in more ways than a clean logout: the client disappears, the connection times out, the server evicts idle sessions, or an exception is thrown halfway through setup. Each of those paths must lead to the same release.
So the rule is to put the release in a finally block when the permit's lifetime is one method call, and to tie it to the session's own end-of-life event when the session outlives the call: the close callback, the expiry listener of the session store, or the scheduled sweeper that removes idle entries. A metric such as slots.availablePermits() compared with activeSessions.size() over time shows a leak quickly, because the two numbers drift apart.
6Testing That the Bound Holds
A limit like this must be proven under concurrency, not reasoned about once. We start many threads together and check the high-water mark.
Running the same test against the original size() version shows the overshoot on most machines within a few runs, which is a convincing before-and-after for a code review.
7Follow-up questions
Why not just synchronize open() and close()?
That works and is easy to reason about, but every session open and close in the service then waits on one lock, even though they touch different sessions. A Semaphore or an atomic counter gives the same hard bound with a single lock-free atomic step, so it scales better under load.
What changes if the service runs on several instances?
A Semaphore only bounds one JVM. For a fleet-wide limit we either divide the limit across instances, for example 250 each on four instances, or keep the count in a shared store such as Redis with an atomic increment and an expiry, accepting the extra network call and the need to clean up counts from crashed instances.
8Conclusion
In this answer, we saw why a limit guarded by activeSessions.size() leaks: the check and the put are separate operations, so many threads pass the check before any of them adds, and size() is only an estimate under concurrent updates anyway, just like mappingCount(). We enforced a hard bound with a Semaphore acquired before adding and with an equivalent AtomicInteger compare-and-set loop, made sure permits are released exactly once in finally blocks or on session expiry, and tested the high-water mark with many concurrent threads.
Open with
The bug is a check-then-act race. size() and the following put are two separate operations, so when the map holds 999 sessions, fifty threads can all read 999, all pass the check, and all put before any of them sees the new size.
Then, if they want more
Each map call is thread-safe, but the decision is out of date by the time the thread acts. On top of that, size() on a ConcurrentHashMap is an estimate while other threads are updating it, because it sums internal counter cells; mappingCount() returns a long but works the same way.
So I would stop using the map's size as the guard. I would use a Semaphore with 1,000 permits and call tryAcquire before adding a session, rejecting the request if it returns false. Taking a permit is atomic, so the bound is hard. An AtomicInteger with a compare-and-set loop gives the same guarantee if I need a plain counter.
The other half of the fix is releasing correctly: the permit must come back exactly once, in a finally block if setup fails, and on logout, timeout or expiry for normal sessions, and only when remove actually removed something, so double closes cannot inflate the limit.
I would add a metric comparing available permits with the map size to catch leaks, and a test that starts a couple of hundred threads together and asserts the maximum concurrent count never goes above 1,000.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8
- 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 rate limiter rejects requests when activeSessions.size() >= 1000, where activeSessions...": https://scrivio-interview-library.netlify.app/java/concurrent-collections/82e8cdb749/