Quick revision
The short answer
The code is a check-then-act race: many threads can read running.get() as 99 before any of them increments, so all of them start a job and the limit is exceeded. The fix is to make the check and the increment one atomic step with a compare-and-set loop that gives up when the count is already 100, and to decrement in a finally block when the job ends. A Semaphore(100) with tryAcquire and release expresses the same limit more directly, and either version should be tested with many threads while recording the highest concurrency observed.
What to remember
In this answer, we saw that get() followed by incrementAndGet() is a check-then-act race, because many threads can pass the check before any of them increments. We fixed it with a compare-and-set loop that rejects when the count is full, made sure the slot is returned in a finally block when the job really ends, replaced the hand-written code with Semaphore.tryAcquire and release, and wrote a test that releases many threads together and asserts the maximum concurrency observed.
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 code is a check-then-act race: many threads can read running.get() as 99 before any of them increments, so all of them start a job and the limit is exceeded. The fix is to make the check and the increment one atomic step with a compare-and-set loop that gives up when the count is already 100, and to decrement in a finally block when the job ends. A Semaphore(100) with tryAcquire and release expresses the same limit more directly, and either version should be tested with many threads while recording the highest concurrency observed.
Why this question is asked
Limiting concurrency is something every backend does: at most 100 report jobs, at most 20 calls to a fragile partner API, at most 8 imports at once. Using an AtomicInteger feels safe because the class name says atomic, and that is exactly the trap. Interviewers like this question because it checks whether we understand that atomic operations are atomic one at a time, not in combination. In this answer, we will see why the original code breaks, fix it with a compare-and-set loop, make sure the count goes back down on every path, rewrite it with a Semaphore, and write a test that would have caught the bug.
1Why Two Atomic Calls Are Not One Atomic Step
running.get() is atomic, and running.incrementAndGet() is atomic, but there is a gap between them in which other threads can run. The code first checks a condition and then acts on it, a pattern known as check-then-act, and the condition can stop being true in between.
Imagine the count is 99 and three threads arrive together. All three call get() and see 99, all three pass the check, and then all three increment, so the count becomes 102 and three jobs start where only one was allowed. Under a burst of requests this is not rare at all; it happens every time arrivals overlap.
2Fix 1: A Compare-and-Set Loop
To close the gap, the check and the increment must happen as one operation. compareAndSet(expected, newValue) does that: it writes newValue only if the value is still expected. So we read the count, check it, and try to move it from that exact value to one more. If another thread changed the count in between, the CAS fails and we start again with the fresh value.
- Read count cfor example 99
- Is c 100 or more?YesReturn false: fullNoTry CAS from c to c + 1
- Did the CAS succeed?YesReturn true: start the jobNoAnother thread changed it; read again
3 steps in order. Play them, or step through them one at a time.
Replay the earlier scenario with this code. All three threads read 99. T1's CAS from 99 to 100 succeeds. T2's CAS from 99 to 100 fails because the value is now 100, so T2 loops, reads 100 and returns false. T3 does the same. Exactly one job starts. The check is now part of the atomic update instead of something done before it.
3Decrementing on Every Path
A limit is only correct if slots are returned. If a job throws an exception and the count is never decremented, the pool of slots leaks one at a time, and after 100 failures nothing can start again. So the decrement belongs in a finally block that runs when the job ends, however it ends.
There is a catch when startJob() only launches the job asynchronously, for example by submitting it to an executor. Then the method returns immediately while the job is still running, and decrementing right after it would make the limit meaningless. In that case the decrement must happen inside the task itself, in its own finally block, or in a whenComplete callback on the CompletableFuture, so that it runs when the work really ends. And if the submission itself fails, for example with a RejectedExecutionException, we must decrement there too.
4Fix 2: Say It With a Semaphore
What we built by hand is exactly what java.util.concurrent.Semaphore provides: a set of permits that threads acquire and release. tryAcquire() takes a permit if one is free and returns false otherwise, without waiting, which matches the original behaviour.
A reader sees the intent at once, and the Semaphore also offers tryAcquire(timeout, unit) if we would rather wait briefly than refuse, plus availablePermits() for a metric. The AtomicInteger version is still useful to understand, because the same CAS loop pattern solves many other 'update only if a condition holds' problems.
5Testing the Limit With Many Threads
Race conditions hide in single-threaded tests, so the test must create real contention: many threads released at the same moment, each trying to start a job that stays running long enough to overlap with others. While jobs run, we record the highest number of concurrent jobs observed and assert that it never passes 100.
With the original check-then-act version this test typically reports a maximum well above 100; with either fix it stays at or below 100. Running it a few times, or with a tool such as jcstress for finer-grained interleavings, raises confidence further.
6Follow-up questions
Would making the method synchronized also fix it?
Yes, wrapping the check and the increment in one synchronized block makes them atomic together, and with a plain int it is perfectly correct. The CAS loop avoids blocking and the Semaphore states the intent; for low rates any of the three is fine.
Can the CAS loop spin forever?
Not in practice. A CAS fails only because another thread succeeded, so the system as a whole always makes progress. An individual thread may retry a few times under heavy contention, which is cheap compared with starting a job.
Why not use incrementAndGet first and decrement if it went over 100?
That also keeps the limit if done carefully, but the count can briefly read above 100, which confuses metrics, and every rejected call does two writes to a contended variable. The CAS loop never lets the count pass the limit.
7Conclusion
In this answer, we saw that get() followed by incrementAndGet() is a check-then-act race, because many threads can pass the check before any of them increments. We fixed it with a compare-and-set loop that rejects when the count is full, made sure the slot is returned in a finally block when the job really ends, replaced the hand-written code with Semaphore.tryAcquire and release, and wrote a test that releases many threads together and asserts the maximum concurrency observed.
Open with
The bug is check-then-act. get and incrementAndGet are each atomic, but there's a gap between them, so if the count is 99 and ten threads arrive together, all ten read 99, all pass the check, and all increment, and we end up with 109 jobs.
Then, if they want more
The fix is to make the check part of the atomic update. I'd write a CAS loop: read the count into c, return false if c is already 100, otherwise compareAndSet from c to c plus one, and loop if that fails.
A failed CAS means another thread changed the count, so we re-check against the new value, and only one thread can move 99 to 100. Just as important is giving the slot back: the decrement goes in a finally block when the job ends.
If startJob only submits asynchronous work, the decrement has to be inside the task or in a completion callback, and also on the path where the submission is rejected. In practice I'd probably use a Semaphore with 100 permits, tryAcquire to start and release in finally, because it says exactly what we mean.
To test it, I'd release a few hundred threads together with a latch, have each job record the current active count into a max with accumulateAndGet, keep jobs running briefly so they overlap, and assert the maximum never goes above 100. The original code fails that test reliably.
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
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
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 "Fix the race in this code that should allow at most 100 concurrent jobs:": https://scrivio-interview-library.netlify.app/java/atomics/2472b82d7f/