A Java service gets slower under load, so the first instinct is to add concurrency. The thread pool has 50 workers; raise it to 100 and throughput improves. Raise it to 200 and it improves a little more. At 500, something changes: latency jumps, the database connection pool fills, requests start waiting, memory rises, garbage collection becomes noticeable, and callers time out, even though the JVM could happily create more threads.
The trap is that concurrency isn't capacity. Threads decide how much work can be in progress, not how much the whole system can finish. A service can schedule hundreds of platform threads, or hundreds of thousands of virtual threads, and still be limited by eight CPU cores, 30 database connections, one contended lock, a rate-limited API or a storage system's operations-per-second ceiling. So instead of asking how many threads a service should have, I find it more useful to ask which resource actually limits throughput, and what happens when concurrency goes past it.
Little's law
Concurrency, throughput and latency are tied together by Little's law:
Here is the average number of requests in progress, is throughput and is the average time per request. JEP 444, the OpenJDK proposal that introduced virtual threads, uses the same example: a service with 50 ms average latency handling 200 requests per second has about 10 requests in progress. To reach 2,000 requests per second at the same latency, it needs about 100 in flight.
So more concurrency really can raise throughput, but only while it lets useful work happen that was otherwise waiting for no good reason. If requests are blocked on I/O while the CPU sits idle, more concurrency helps a lot. If the database is already saturated, more callers just give it a longer queue.
When concurrency helps
Take a request that spends 5 ms computing and 45 ms waiting for the database. A synchronous thread spends most of its life waiting:
With one worker, the CPU is idle most of the time. More concurrent requests let other work use the CPU while one waits on the network:
That's why a thread-per-request service can benefit from far more concurrent requests than it has cores: the waiting overlaps with useful work elsewhere.
Now change the workload so each request does 50 ms of pure CPU work on an eight-core machine. Eight tasks keep eight cores busy; 800 tasks don't create 792 more CPUs. Past the number of cores, you just get more runnable work than processors, with more scheduling and context switching and no extra compute. JEP 444 is explicit about this: virtual threads aren't faster threads. They help workloads with many concurrent tasks that spend a lot of time waiting, and they do nothing for CPU-bound code. Concurrency helps when work can overlap; it doesn't add capacity inside the bottleneck itself.
The pool that actually matters
A typical Spring service has several pools in a row:
Say Tomcat allows 200 request threads, HikariCP has 20 database connections, and nearly every request needs the database:
server:
tomcat:
threads:
max: 200
spring:
datasource:
hikari:
maximum-pool-size: 20
In practice that's 200 threads funnelling into 20 connections. Raising Tomcat to 500 doesn't give the database more capacity; it lets another 300 callers compete for the same 20 connections. Tuning only the most visible executor is misleading, because the thread pool is just one of several concurrency limits.
The next instinct is to enlarge the database pool too. Sometimes that's right, but a connection pool is another concurrency control, not a source of throughput. HikariCP's About Pool Sizing argues that you want a small pool saturated with threads waiting for connections, and suggests starting around (core_count * 2) + effective_spindle_count and testing from there. A database with eight cores can stay busy with a modest number of active queries. Five hundred active queries all fight over the same CPU, buffer cache, locks, disk and memory, and throughput stops rising while latency keeps climbing. Size the database pool by how much concurrent work the database can do efficiently, not by how many application threads exist. The same goes for almost any shared dependency.
Finding the knee of the curve
Here's an illustrative load test:
| Concurrent requests | Throughput | p95 latency |
|---|---|---|
| 10 | 180 req/s | 70 ms |
| 25 | 410 req/s | 85 ms |
| 50 | 690 req/s | 120 ms |
| 100 | 850 req/s | 240 ms |
| 200 | 880 req/s | 700 ms |
| 400 | 840 req/s | 2.1 s |
Up to 100 concurrent requests, each step adds real throughput. From 100 to 200, throughput barely moves (850 to 880) while p95 latency nearly triples. At 400, throughput actually drops and latency reaches seconds. That turning point is the knee of the curve. Past it, extra concurrency mostly adds queueing, contention, memory pressure, context switching and timeouts.
The knee is far more useful to know than the maximum number of threads the JVM can create. Capacity planning is about staying in the region where concurrency still produces useful work with acceptable latency and some headroom.
That headroom matters. If 100 concurrent requests give 950 req/s with a 300 ms p99, and 500 give 975 req/s with a 4-second p99, I'd usually choose the first. A 2.6% throughput gain cost a more than 13-fold increase in p99, plus more queueing, more live memory and a sharper failure when a dependency slows. Running right at saturation means ordinary variation (a slow query, a cache miss, a deploy, a GC cycle, a traffic burst) pushes the service over the knee.
Queues hide latency
An executor has two controls, its workers and its queue:
ExecutorService executor =
new ThreadPoolExecutor(
32,
32,
0L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1000)
);
At low traffic, a request finds a free worker and runs straight away. Under overload, it waits in the queue first. With 32 workers, 1,000 queued requests and 100 ms per request, a request at the back waits around three seconds before a worker even looks at it. If the client's deadline is one second, the server will eventually spend CPU, database time and downstream calls on a request whose caller has already given up. That's wasted capacity.
The Google SRE chapter on addressing cascading failures describes the same pattern: when capacity falls short, queues grow, latency rises and queued work consumes more resources. A smaller queue can give a healthier service because excess work is rejected before it spends its deadline waiting. A queue isn't spare capacity; it's stored waiting.
Java also makes it easy to create a queue with no practical limit. Executors.newFixedThreadPool(32) gives you 32 workers and an unbounded queue. If work keeps arriving faster than it finishes, the queue absorbs the difference, latency rises, queued objects pile up, memory and GC pressure grow, and eventually OutOfMemoryError becomes possible. A bounded executor makes the saturation point explicit:
ThreadPoolExecutor executor =
new ThreadPoolExecutor(
32,
32,
0L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(128),
new ThreadPoolExecutor.AbortPolicy()
);
With all 32 workers busy and 128 tasks waiting, it refuses new work. Rejecting a request while the JVM still has memory can feel harsh, but under sustained overload a fast rejection is much healthier than waiting 15 seconds and timing out anyway. The bounded queue turns overload into a visible decision instead of hiding it in latency and heap growth.
Locks, waits and memory
Sometimes CPU and the database are fine and the limit is in the code:
public synchronized void process(Order order) {
validate(order);
calculate(order);
persist(order);
}
Every request has to enter the same monitor. A hundred threads may exist, but only one makes progress through that method at a time; the other 99 wait. Add another hundred threads and you've added another hundred waiters. A service can look highly concurrent to the scheduler and be effectively serial at the resource that matters.
Contention is rarely that obvious. Threads might be waiting on connection pools, shared maps, database row locks, rate limiters, file operations, a single-threaded SDK, logging appenders, hot cache keys or shared queues. When more concurrency stops helping, the best question is: what are the threads actually waiting on? A thread dump answers it far better than an overall CPU figure:
"http-nio-8080-exec-52"
WAITING
at com.zaxxer.hikari.pool.HikariPool.getConnection(...)
"http-nio-8080-exec-53"
BLOCKED
at com.example.InventoryService.reserve(...)
"http-nio-8080-exec-54"
RUNNABLE
at com.example.PricingEngine.calculate(...)
These are three different problems: the first is waiting for a database connection, the second for a lock, and the third may genuinely be CPU-bound. Raising the global thread count treats them all the same, which is why it's worth identifying the bottleneck before tuning threads.
More concurrency also means more live state at once: request objects, JSON trees, buffers, temporary collections, query results. Even when each request is modest, more of them in flight changes the allocation rate, heap occupancy, object lifetimes and garbage collection, and at scale GC becomes part of your latency. Uber's JVM tuning article has good examples from their data platform, including Hive Metastore getTable calls spiking to three seconds when they should take under 50 ms, and GC tuning on Presto's coordinators to improve reliability. The lesson isn't "tune the GC whenever Java is slow". It's that memory and GC belong in the same performance model as CPU, threads, queues and dependencies. Fixing one limit often just reveals the next:
Virtual threads
Java 21 made virtual threads final through JEP 444. Platform threads map closely to operating-system threads and are relatively expensive. Virtual threads are much lighter: when one blocks on a supported operation, the JVM parks it and frees the underlying carrier thread for other work. That lets you write plain blocking code while supporting very high I/O concurrency:
try (var executor =
Executors.newVirtualThreadPerTaskExecutor()) {
Future<Customer> customer =
executor.submit(() ->
customerClient.fetch(customerId)
);
Future<List<Order>> orders =
executor.submit(() ->
orderClient.fetch(customerId)
);
return new Dashboard(
customer.get(),
orders.get()
);
}
For I/O-heavy services that's a big improvement; you no longer need a large platform-thread pool just to represent lots of blocked tasks. But virtual threads make waiting cheap. They don't make dependencies bigger.
If 100,000 virtual threads all reach jdbcTemplate.query(...) and HikariCP has 20 connections, database concurrency is still about 20, and the rest wait for a connection. JEP 444 specifically warns against pooling virtual threads to limit concurrency. Create them per task, and protect scarce resources with tools built for that, such as semaphores:
private final Semaphore downstreamSlots =
new Semaphore(20);
public Result callDependency() throws Exception {
downstreamSlots.acquire();
try {
return dependency.call();
} finally {
downstreamSlots.release();
}
}
Now application concurrency can be very high while downstream concurrency is deliberately bounded, and one arbitrary pool size no longer has to stand in for several unrelated limits.
Virtual threads can actually expose weak capacity planning. With 200 platform threads, a service had an accidental limit: only 200 operations could block at once. Switch to virtual threads and 10,000 tasks can wait cheaply. That's great if platform threads were the bottleneck, and dangerous if all 10,000 now hit the same finite dependency:
Virtual threads remove one scarcity, the OS thread, and make the remaining ones easier to reach. That makes capacity reasoning more important, not less.
Limits per resource
A request path might allow 500 HTTP requests, have 8 cores of useful CPU, 30 database connections and 50 permitted calls to an external API. Which number should "the thread pool" be? The question assumes one number can represent several different resources:
Different phases of a request compete for different resources, so limits per resource are usually more useful than one global thread count.
This is also how you stop one slow dependency from starving the rest. If payment, recommendation and email calls all share one executor of 300 threads, a slow recommendation service can eventually tie up most of them, and payments lose capacity even though the payment provider is healthy. A bulkhead gives each dependency its own allowance:
With platform threads that might be separate executors; with virtual threads, separate semaphores are often cleaner. The semaphore isn't the important part; isolating failure domains is.
Putting it together, independent calls can overlap freely while the scarce one gets a limit that fails fast:
private final Semaphore inventoryLimit =
new Semaphore(50);
private Inventory getInventory(String orderId)
throws Exception {
if (!inventoryLimit.tryAcquire(
100,
TimeUnit.MILLISECONDS)) {
throw new ServiceBusyException(
"Inventory capacity exhausted"
);
}
try {
return inventoryClient.get(orderId);
} finally {
inventoryLimit.release();
}
}
That expresses two separate ideas: create concurrency freely where it's cheap, and bound it where resources are scarce. "Thread pool size = 200" doesn't correspond to anything real; "50 concurrent inventory calls" does.
Load shedding
Suppose a service can sustain 1,000 requests a second and receives 1,500. If it admits all of them into a big queue, the queue grows, latency grows, deadlines are missed, clients retry and more work arrives. It can end up completing fewer than 1,000 useful requests a second, because overload eats resources that could have gone to work that would finish. The SRE cascading-failures chapter describes exactly this mix of long queues, thread starvation, missed deadlines and retries feeding each other.
Admission control at the front keeps the healthy part working:
It's counterintuitive, but rejecting some work can let the system complete more useful work.
Diagnosing a slow service
If more threads stop adding throughput, I don't tune the executor again straight away. First I look at where requests are spending their time:
| Signal | Possible bottleneck |
|---|---|
| CPU near 100% | CPU-bound workload |
| One core saturated | A hot thread, serial section or lock |
| High runnable-thread count | CPU contention |
| Many blocked threads | Lock contention |
| Many threads waiting on HikariCP | Database connection limit |
| Database CPU high | Database processing capacity |
| Database lock waits high | Transaction contention |
| Executor queue growing | Not enough processing capacity |
| Long GC pauses | Allocation, heap or GC pressure |
| Downstream latency rising | A dependency is the bottleneck |
| p99 rising while throughput is flat | Saturation or queueing |
| Throughput falling as concurrency rises | Contention or overload |
Watch the tail, not the average. With p50 at 90 ms, p95 at 240 ms and p99 at 4.2 seconds, half the requests are fast while one in a hundred callers is using a completely different service. Saturation usually shows up there first, from queueing, connection waits, lock contention or GC pauses hitting unlucky requests, and that tail is where timeouts and retries start.
Then load test in steps (10, 25, 50, 100, 200, 500 concurrent requests) instead of one big stress run, and at each step line up throughput, p50/p95/p99, CPU, runnable threads, queue depth, active database connections and connection wait time, GC pauses, downstream latency and rejections. A thread count tells you how much concurrency the system allows. Only these measurements tell you whether that concurrency is useful.
Key takeaways
- Little's law ties concurrency, throughput and latency together. More concurrency only helps while there's idle capacity to use, usually because work is waiting on I/O.
- The thread pool is rarely the real limit. Find which pool or resource requests are waiting on (database connections, a lock, CPU, a dependency) before tuning threads.
- Keep database pools small and sized to the database, not to the number of application threads.
- Bound queues and shed load early; a fast rejection beats a slow timeout.
- Virtual threads make waiting cheap but don't make dependencies bigger. Use semaphores to limit each scarce resource.
- Load test in steps to find the knee of the curve, watch tail latency, and run with headroom below it.
References
- OpenJDK — JEP 444: Virtual Threads — Little's law, why virtual threads help waiting rather than computing, and the advice to limit concurrency with semaphores instead of pools.
- HikariCP — About Pool Sizing — why small, saturated connection pools tend to outperform large ones, with a starting formula.
- Google SRE — Addressing Cascading Failures — how queue growth, thread starvation, deadlines and retries interact under overload.
- Uber — Tricks of the Trade: Tuning JVM Memory for Large-scale Services — real cases where GC and heap behaviour affected latency and reliability.
