Java applications often use multiple threads to handle incoming requests, execute background tasks, communicate with databases, and call external services. As application traffic increases, managing a large number of concurrent operations can become difficult.
Traditional platform threads are backed by operating system threads. Creating and maintaining large numbers of platform threads consumes memory and operating system resources. Developers commonly use thread pools to control the number of active threads, but this can limit how many tasks an application processes concurrently.
Java virtual threads provide another approach. They are lightweight threads managed by the Java runtime rather than being directly tied to individual operating system threads.
Virtual threads became a permanent feature in Java 21 through Project Loom. They allow developers to build high-throughput applications using a straightforward thread-per-task programming model.
However, introducing virtual threads into a production application requires more than changing an executor configuration. Developers must understand where virtual threads provide benefits, how to manage limited resources, how to identify performance problems, and how to monitor concurrency.
This article explains how to use Java virtual threads in production applications with practical examples and implementation guidance.
Understanding Java Virtual Threads
Java provides two main types of threads: platform threads and virtual threads.
A platform thread is backed by an operating system thread. When a platform thread performs a blocking operation, such as waiting for a database response, it generally occupies its operating system thread until the operation completes.
A virtual thread is managed by the Java runtime. It runs on a platform thread called a carrier thread. When a virtual thread performs a supported blocking operation, the runtime can suspend it and release the carrier thread to execute another virtual thread.
When the operation becomes ready, the virtual thread can resume execution on an available carrier.
This scheduling model allows an application to support many more concurrent tasks without creating an equivalent number of operating system threads.
For example, imagine an API that handles thousands of incoming requests. Each request may call a database, retrieve information from another service, and prepare a response. Most of the processing time may be spent waiting for network operations.
With traditional platform threads, a large number of waiting requests can consume a significant number of operating system threads. Virtual threads allow those waiting tasks to suspend without holding on to a carrier thread in the same way.
The main benefit is improved scalability and throughput, not faster execution of individual Java instructions.
Creating Virtual Threads in Java
Java provides several ways to create virtual threads. The Thread API is useful when you want to start an individual virtual thread directly.
For example:
public class VirtualThreadExample {
public static void main(String[] args)
throws InterruptedException {
Thread thread = Thread.ofVirtual().start(() -> {
System.out.println(
"Running on: " +
Thread.currentThread()
);
});
thread.join();
}
}
The Thread.ofVirtual() method creates a virtual thread builder. The start() method starts the thread immediately.
The join() method makes the main thread wait until the virtual thread finishes.
This approach is suitable for small examples and individual tasks. Production applications generally benefit from using an ExecutorService because it provides a consistent way to submit tasks and manage their completion.
Using a Virtual Thread Per Task Executor
The Executors.newVirtualThreadPerTaskExecutor() method creates an ExecutorService that starts a new virtual thread for every submitted task.
Consider an application that needs to retrieve information from multiple external services.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ServiceAggregator {
public static void main(String[] args)
throws Exception {
try (ExecutorService executor =
Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> userFuture =
executor.submit(() -> getUser());
Future<String> orderFuture =
executor.submit(() -> getOrders());
Future<String> paymentFuture =
executor.submit(() -> getPayments());
System.out.println(userFuture.get());
System.out.println(orderFuture.get());
System.out.println(paymentFuture.get());
}
}
private static String getUser() {
return "User information received";
}
private static String getOrders() {
return "Order information received";
}
private static String getPayments() {
return "Payment information received";
}
}
Each submitted operation runs in its own virtual thread.
The application can execute independent operations concurrently instead of waiting for one operation to finish before starting another.
The try-with-resources statement automatically closes the executor. Closing the executor waits for submitted tasks to finish before the program continues beyond the block.
This pattern is useful for service aggregation, independent database operations, and other workloads where tasks spend significant time waiting for I/O.
Using Virtual Threads in Spring Boot Applications
Spring Boot applications frequently handle requests that involve database access, external HTTP calls, and other blocking operations.
Virtual threads can be useful for applications that use a traditional synchronous request-processing model.
Spring Boot provides a configuration property for enabling virtual threads when running on a supported Java version.
For example, in application.properties:
spring.threads.virtual.enabled=true
With virtual threads enabled, supported Spring Boot infrastructure can use virtual threads for task execution.
The exact behavior depends on the Spring Boot version and the application components being used. Review the documentation for your version before enabling the setting in production.
For a service-level example, consider a component that retrieves customer information from an external API.
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
@Service
public class CustomerService {
private final RestClient restClient;
public CustomerService(RestClient.Builder builder) {
this.restClient = builder
.baseUrl("https://api.example.com")
.build();
}
public String getCustomer() {
return restClient.get()
.uri("/customers/101")
.retrieve()
.body(String.class);
}
}
This service uses a synchronous HTTP call. When the underlying HTTP operation blocks in a way supported by the runtime, a virtual thread can suspend while waiting for the response.
This allows the application to handle more concurrent requests without requiring a large number of platform threads.
However, virtual threads do not automatically remove bottlenecks in HTTP connection pools, database connection pools, or external services. Those resources still need appropriate configuration.
Managing Database Connections With Virtual Threads
Database access is one of the most important areas to consider when adopting virtual threads.
A virtual thread can wait efficiently for a database response, but it cannot create unlimited database connections.
For example, an application may support thousands of concurrent virtual threads while its database connection pool allows only 30 active connections.
The remaining requests must wait for an available connection.
This is normal. The database connection pool protects the database from excessive concurrent connections.
Consider a service using JDBC:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
public class CustomerRepository {
private final DataSource dataSource;
public CustomerRepository(DataSource dataSource) {
this.dataSource = dataSource;
}
public String findCustomer(int id) throws Exception {
String sql =
"SELECT name FROM customers WHERE id = ?";
try (Connection connection =
dataSource.getConnection();
PreparedStatement statement =
connection.prepareStatement(sql)) {
statement.setInt(1, id);
try (ResultSet result = statement.executeQuery()) {
if (result.next()) {
return result.getString("name");
}
}
}
return null;
}
}
When this method runs on a virtual thread, the JDBC driver and database interaction determine how blocking behavior is handled.
The connection pool remains responsible for limiting the number of database connections.
Production applications should monitor connection acquisition time, active connections, idle connections, and query execution time.
If virtual threads allow more requests to reach the database simultaneously, a database that was previously protected by a small platform thread pool may experience increased pressure.
Virtual threads improve the application's ability to wait. They do not increase the database's processing capacity.
Limiting Access to External Services
Another common production requirement is controlling how many requests can access an external service at the same time.
For example, a payment provider may allow only 20 concurrent requests for a particular operation.
A traditional fixed thread pool is sometimes used to limit concurrency. With virtual threads, a semaphore is a more direct way to control access to a limited resource.
import java.util.concurrent.Semaphore;
public class PaymentService {
private final Semaphore semaphore =
new Semaphore(20);
public String processPayment() throws InterruptedException {
semaphore.acquire();
try {
return callPaymentProvider();
} finally {
semaphore.release();
}
}
private String callPaymentProvider() {
return "Payment processed";
}
}
The semaphore allows up to 20 operations to enter the protected section at the same time.
Additional virtual threads wait until a permit becomes available.
The finally block is important because it releases the permit even when the external operation fails.
This pattern can also be used for rate-sensitive services, limited hardware resources, and other operations that require explicit concurrency control.
A semaphore limits concurrent operations, not requests per second. If an external provider enforces a rate limit, implement an appropriate rate-limiting strategy as well.
Understanding Virtual Thread Pinning
Virtual threads depend on the runtime's ability to release carrier threads when a virtual thread blocks.
In certain situations, a virtual thread can become pinned to its carrier. When this happens, the carrier cannot be released during the blocking operation.
Native methods and foreign function calls are important situations where pinning can occur.
Pinning does not automatically make an application incorrect, but frequent or long-lasting pinning can reduce scalability.
Older Java versions also had important pinning considerations around blocking operations performed inside synchronized sections. Java 24 changed the monitor implementation so that ordinary monitor-related pinning was substantially reduced. Native and foreign function calls remain relevant considerations.
For example, consider code that performs a slow network operation while holding a synchronized lock:
public synchronized void processRequest() {
// Shared resource is protected.
callExternalService();
}
The problem is not simply that synchronized exists. The larger design concern is holding a shared lock while waiting for an external operation.
This can prevent other threads from accessing the protected resource and increase request delays.
A better approach is to keep synchronized sections short and avoid performing slow I/O while holding a lock.
public void processRequest() {
String requestData;
synchronized (this) {
requestData = prepareRequestData();
}
callExternalService(requestData);
}
This example moves the external operation outside the synchronized section.
Review actual thread behavior and runtime diagnostics before changing synchronization mechanisms. Do not replace every synchronized block with another locking mechanism without understanding its purpose.
Avoiding Thread-Local Memory Problems
ThreadLocal variables are commonly used to store data associated with a thread, such as request context, user information, or reusable objects.
With platform thread pools, a limited number of threads may be reused across many tasks.
Virtual threads are different. An application can create a very large number of them, and each task generally has its own virtual thread.
This means that using ThreadLocal to cache expensive objects can increase memory consumption.
For example, creating a separate expensive formatter for every virtual thread may use significantly more memory than expected.
When an object is immutable and thread-safe, prefer sharing a common instance.
import java.time.format.DateTimeFormatter;
public class DateFormatter {
private static final DateTimeFormatter FORMATTER =
DateTimeFormatter.ISO_LOCAL_DATE_TIME;
public String formatDate(
java.time.LocalDateTime dateTime) {
return FORMATTER.format(dateTime);
}
}
DateTimeFormatter is immutable and thread-safe, so the same instance can be safely shared across threads.
Thread-local storage can still be useful for request-specific context, but developers should review its memory impact and lifecycle carefully.
Monitoring Virtual Threads in Production
Monitoring is essential when introducing virtual threads into an application.
A service may successfully create thousands of virtual threads but still experience slow responses because of database contention, external service delays, memory pressure, or carrier thread starvation.
The JDK provides tools for investigating virtual thread behavior.
Generating Thread Dumps
The jcmd utility can generate a thread dump for a running Java process.
jcmd <pid> Thread.print
For a thread dump that includes virtual threads in text or JSON format, use:
jcmd <pid> Thread.dump_to_file -format=text threads.txt
Or:
jcmd <pid> Thread.dump_to_file -format=json threads.json
These dumps help developers investigate blocked operations, thread states, and application hangs.
Monitoring With Java Flight Recorder
Java Flight Recorder provides events that help identify virtual thread behavior.
Important events include:
jdk.VirtualThreadStart records virtual thread creation.
jdk.VirtualThreadEnd records virtual thread completion.
jdk.VirtualThreadPinned identifies virtual threads that remain pinned beyond the configured threshold.
jdk.VirtualThreadSubmitFailed records failures when submitting or resuming virtual threads.
These events can help identify unexpected thread behavior and resource-related problems.
Monitoring the Virtual Thread Scheduler
The JDK also provides diagnostic commands for observing the virtual thread scheduler.
jcmd <pid> Thread.vthread_scheduler
This command provides information about scheduler activity and can help investigate scheduling problems.
Use these tools alongside application metrics such as request latency, throughput, database connection usage, CPU utilization, and memory consumption.
Common Mistakes When Using Virtual Threads
Assuming Virtual Threads Make Every Application Faster
Virtual threads are designed to improve scalability for workloads with many concurrent tasks that spend time waiting.
CPU-intensive workloads do not automatically become faster. They may still be limited by the number of available CPU cores.
Pooling Virtual Threads
Virtual threads are designed to represent individual tasks. Creating a fixed pool of virtual threads usually defeats the purpose of the virtual thread-per-task model.
Use Executors.newVirtualThreadPerTaskExecutor() for task execution. Use semaphores or other resource-specific controls when concurrency needs to be limited.
Ignoring Database and HTTP Connection Limits
A large number of virtual threads can increase the number of operations waiting for database connections or external HTTP resources.
Configure connection pools and concurrency limits based on the capacity of the downstream systems.
Performing Long Operations While Holding Locks
Holding locks during slow network or database operations can create unnecessary contention.
Keep critical sections short and avoid waiting for external resources while holding shared locks.
Ignoring Memory Usage
Virtual threads are lightweight, but they are not free. Each thread still has associated runtime state and may retain objects through its stack and references.
Creating an unbounded number of tasks can still exhaust application memory.
Skipping Production Load Testing
A successful local test does not prove that virtual threads will improve production performance.
Test realistic request volumes, downstream service delays, database limits, and failure scenarios before deploying the change.
Best Practices for Production Applications
Use virtual threads for workloads that contain many concurrent blocking I/O operations. They are especially useful for request-per-thread server applications and service integrations.
Create a virtual thread for each concurrent task rather than maintaining a pool of virtual threads.
Keep resource limits separate from thread management. Use connection pools for database connections and semaphores when a particular external operation needs a concurrency limit.
Avoid unnecessary ThreadLocal caching of expensive objects. Prefer immutable shared objects when possible.
Keep synchronized sections short and investigate long-running pinned operations through Java Flight Recorder and thread dumps.
Monitor the entire application rather than only thread counts. Database performance, HTTP connection usage, memory consumption, CPU utilization, and request latency remain important.
Finally, introduce virtual threads gradually. Compare application behavior before and after the change under realistic production-like workloads.
Conclusion
Java virtual threads provide a practical way to build applications that handle large numbers of concurrent tasks without requiring an equivalent number of operating system threads.
They work particularly well for applications that spend significant time waiting for database queries, HTTP responses, and other blocking I/O operations.
However, virtual threads do not remove resource limitations. Database connections, external APIs, CPU capacity, and memory still need careful management.
For production applications, the best approach is to use a virtual thread per task, control access to limited resources independently, monitor thread behavior, and test under realistic workloads.
When implemented with these considerations, virtual threads can simplify Java concurrency and help applications handle higher levels of concurrent traffic.
Join the conversation! Your thoughts help the community grow.