Sub topic 2
What Changes Once the Property Is Set
Assume Java 21 or newer, Spring Boot 3.2 or later, and a Spring MVC application using blocking JDBC or HTTP clients. You should also understand ExecutorService and basic blocking I/O.
What Changes Once the Property Is Set
Add this property:
spring.threads.virtual.enabled=trueSpring Boot then configures its application task executor to create a new virtual thread for each task. With a supported embedded server, such as Tomcat, request processing also uses virtual threads.
A virtual thread is a JVM-managed thread designed to make blocking code inexpensive. It runs on a smaller set of operating-system threads called carrier threads. When the virtual thread waits for I/O, the JVM can unmount it from its carrier and run another virtual thread there.
Your controller code usually does not change. A blocking call such as a JDBC query still blocks the current virtual thread, but it does not normally occupy a carrier thread while the database is responding.
When Virtual Threads Help and When They Do Not
Virtual threads fit workloads with many concurrent operations that spend time waiting:
- Database queries
- HTTP calls to other services
- File or socket operations
- Spring MVC requests that combine several blocking calls
They do not make CPU work faster. Encryption, image processing, compression, and large in-memory calculations still compete for a limited number of processor cores. For those tasks, bounded platform-thread pools or other CPU-aware designs remain important.
Virtual threads also do not increase the capacity of a database or downstream service. They remove thread-pool pressure, which can expose the next bottleneck sooner.
Protecting Databases and Downstream Services
A traditional thread pool may have accidentally limited concurrency. After switching to virtual threads, thousands of requests can reach a database at once. Use a connection pool and an explicit limit for scarce operations.
A Semaphore is a counter of permits. Acquire a permit before the operation and release it in finally, so failures do not permanently reduce capacity.
private final Semaphore permits = new Semaphore(20);
String stockFor(String sku) throws InterruptedException {
permits.acquire();
try {
return inventoryClient.stockFor(sku);
} finally {
permits.release();
}
}Choose the permit count from the downstream service's capacity, latency, and connection limits. Monitor rejected, queued, and timed-out work during load testing.
Exercise
Why can enabling virtual threads cause a database overload even when application CPU usage is low?
Show answer
Virtual threads allow more requests to wait concurrently, removing the old thread-pool limit. Without a database connection limit or semaphore, too many requests can reach the database at once.