Sub topic 14
A checklist for a safe rollout
This chapter turns the earlier material into a rollout procedure. It assumes you have a Spring Boot 3.2+ MVC application on Java 21 with Tomcat or Jetty. It also assumes you have read the chapters on pinning, ThreadLocal state, concurrency limits, and observability. Here you will put those pieces in order, decide what to measure, and plan how to back out.
Why a checklist
Enabling virtual threads takes one property. The risk is in what that property changes. The request thread limit stops being the cap on concurrency, so load that used to queue in Tomcat now reaches your database, your HTTP clients, and your locks. Problems that were hidden by a 200-thread cap can show up at once.
A staged rollout makes each of those effects visible one at a time, with a clear way back at every step.
Step 1: Audit before you enable
Do the audit with the property still off. Three areas matter.
Runtime and framework versions
- Confirm the application runs on Java 21 or newer. On older versions the property has no effect for the web server.
- Confirm Spring Boot is 3.2 or later. Earlier versions do not recognize
spring.threads.virtual.enabled. - Note the JDK version precisely. On Java 21 to 23, blocking inside
synchronizedpins the carrier thread. Later JDK releases removed most of that pinning, so the risk depends on your version.
Blocking inside `synchronized`
Search your own code for synchronized blocks and methods that perform I/O, call remote services, or wait on queues. A virtual thread that blocks inside one holds its carrier thread for the whole wait. The fix is to replace the lock with a ReentrantLock, as shown earlier in this tutorial. Do this only for sections that block. A short synchronized section that only updates memory is fine.
Dependencies are harder to audit. Older JDBC drivers, connection pools, and client libraries may block inside synchronized. Check release notes for virtual thread support, and rely on staging tests (Step 3) to find the rest.
`ThreadLocal` usage
Each request now runs on its own short-lived thread, so thread-locals are never reused across requests. Review these patterns:
- Caching expensive objects in a
ThreadLocal(formatters, parsers, buffers). The cache no longer amortizes cost, and memory grows with the number of live threads. - Relying on a thread-local being cleared by pool reuse. The risk is reversed here, since a fresh thread starts empty. Code that expects leftover state breaks.
- Context propagation, such as MDC for logging or security context. Confirm each value is still set at the start of the request and copied explicitly into any task you hand to another executor.
Step 2: Set explicit limits first
With platform threads, server.tomcat.threads.max capped concurrency, and the default is 200. With virtual threads, that cap no longer limits requests in flight. Replace it with limits you choose on the scarce resources.
The most common one is the database connection pool. HikariCP defaults to 10 connections. If thousands of virtual threads wait for a connection, each waits up to the connection timeout, then fails. Set the pool size from what the database can serve, and set a timeout that fails fast.
spring.threads.virtual.enabled=true
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.connection-timeout=2000For downstream services that are not pooled, cap concurrent calls with a Semaphore around the client, as in the LimitedInventoryClient example from the concurrency limits chapter. Choose the permit count from the downstream service's documented capacity, not from a guess.
| Resource | Limit mechanism | Where to set it |
|---|---|---|
| Database | Connection pool size and timeout | `spring.datasource.hikari.*` |
| Internal or third-party HTTP service | `Semaphore` or client connection limit | Client wrapper class |
| CPU-heavy work | Bounded platform thread pool | Dedicated `ExecutorService` |
| Inbound traffic | Rate limiting at gateway or filter | Gateway or application filter |
> Do not size a pool by asking how many requests you expect. Size it by asking how many calls the downstream resource can handle at once.
If you run CPU-heavy work, keep it on a bounded pool of platform threads. Virtual threads give no speedup for CPU-bound code, and thousands of them compete for the same few cores.
Step 3: Enable in staging and verify
Set the property in staging only. Then confirm it took effect, using the endpoint from the enabling chapter:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class ThreadInfoController {
@GetMapping("/thread")
String thread() {
Thread current = Thread.currentThread();
return "virtual=" + current.isVirtual() + ", thread=" + current;
}
}The response should say virtual=true. If it says false, check the Java version, the Boot version, and whether another configuration class defines its own Executor or Tomcat customizer that overrides Boot's.
Remove or protect this endpoint before production. It is a diagnostic aid, not part of the application.
Check the other executors
The property also moves Boot's auto-configured application task executor to virtual threads, so @Async methods and other tasks that use it change too. Any executor you define yourself stays as written. Review each custom ThreadPoolTaskExecutor and decide whether it should stay bounded (for CPU work or rate control) or move to virtual threads.
Step 4: Load test and observe
Run the same load test you ran before the change, then increase the concurrency beyond the old thread cap. Record these values for both configurations so you can compare them.
- Throughput and latency percentiles (p50, p95, p99).
- Error rate, especially connection timeouts from the pool.
- Pool metrics: active connections, pending threads, and acquisition time.
- Heap use and garbage collection pauses, which reveal thread-local growth.
Look for pinning
On Java 21, start the application with the pinning trace, and take a thread dump that includes virtual threads:
java -Djdk.tracePinnedThreads=full -jar app.jar
jcmd <pid> Thread.dump_to_file -format=json threads.jsonThe trace prints a stack when a virtual thread blocks while pinned, and the frames marked in it show the synchronized block or native call responsible. Note that the system property was removed in later JDK releases. There, use JFR.
JFR records a jdk.VirtualThreadPinned event when a virtual thread stays pinned longer than a threshold (20 ms by default). Start a recording during the load test and look for these events. A few short pins are normal. A steady stream from one call site is a defect to fix before the rollout continues.
Interpret the results
| Observation | Likely cause | Action |
|---|---|---|
| Throughput unchanged, CPU saturated | Workload is CPU-bound | Keep platform threads for this service |
| Many connection timeout errors | Pool smaller than concurrent demand | Raise the pool within database capacity, or add a queue-limiting semaphore |
| Frequent pinned-thread events | Blocking inside `synchronized` | Switch to `ReentrantLock`, or upgrade the dependency or JDK |
| Heap grows with traffic | Large objects in `ThreadLocal` | Remove the cache, pass objects explicitly |
| Downstream service returns 429 or 503 | No limit on outbound calls | Add a `Semaphore` or client limit |
Step 5: Canary in production
Release to a small share of instances first. Keep the old configuration on the rest so you can compare the two groups under real traffic.
- Deploy the change to one instance or a small percentage of traffic.
- Watch the same metrics as in staging for at least one full traffic cycle, including peak hours.
- Compare error rate and latency percentiles against the unchanged instances.
- Expand in steps only if every check holds.
Plan the rollback
Rollback is a configuration change. Set spring.threads.virtual.enabled=false (or remove it) and restart. Because you never changed the application's logic to require virtual threads, the service returns to the platform-thread model. Keep this step ready in your deployment tooling, and keep any ReentrantLock or Semaphore changes in place, since they are safe in both models.
Final checklist
- The JDK is 21 or newer and Boot is 3.2 or newer.
synchronizedblocks that perform blocking calls are replaced withReentrantLock, or the JDK version is known to avoid the pinning.ThreadLocalcaches are removed or justified, and context is propagated explicitly.- Database pool size and timeout are set from database capacity.
- Outbound calls to limited services are capped with a semaphore or client limit.
- CPU-bound work runs on a bounded platform-thread pool.
- Staging shows
virtual=trueon the diagnostic endpoint. - Load tests beyond the old thread cap show no unexplained errors and no recurring pinning events.
- A canary comparison covers a full traffic cycle.
- A rollback path is documented and tested.
Exercise
After enabling virtual threads in staging, your load test at 5,000 concurrent users shows many errors that say a database connection could not be obtained within the timeout. CPU use is low. What is the most likely cause, and what are two reasonable fixes?
Show answer
The old Tomcat thread cap (200 by default) used to hold concurrency below the size of the connection pool. With virtual threads, thousands of requests reach the pool at once, and the default HikariCP size (10) cannot serve them within the timeout. Reasonable fixes: raise spring.datasource.hikari.maximum-pool-size to a value the database can handle, or add a limit before the database call, such as a Semaphore or an inbound rate limit, so excess requests wait or are rejected early instead of timing out inside the pool.
Exercise
Your JFR recording during the load test shows a steady stream of jdk.VirtualThreadPinned events from one class on Java 21. Describe how you would diagnose and fix it.
Show answer
Read the stack trace in the event to find the frame inside a synchronized block or a native call that blocks. If it is your code, replace the synchronized section with a ReentrantLock around the blocking part. If it is a dependency, upgrade it to a version that supports virtual threads, or move to a JDK release that removes most synchronized pinning. Then repeat the load test and confirm the events stop.