0 day streak
java / expert
Snippet

Enabling Virtual Threads for Scalable Blocking I/O

Leveraging Java 21+ Virtual Threads in Spring Boot 3.2+ allows the application to handle thousands of concurrent blocking connections without the memory overhead of platform threads, providing reactive-like scalability with imperative code.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
@ConditionalOnThreading(Threading.VIRTUAL)
public class ThreadingConfig {
@Bean
public TomcatProtocolHandlerCustomizer<?> protocolHandlerCustomizer() {
return protocolHandler -> {
protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
};
}
}
// application.properties
// spring.threads.virtual.enabled=true
spring
Breakdown
1
Executors.newVirtualThreadPerTaskExecutor()
Creates an executor that starts a new virtual thread for each submitted task.
2
protocolHandler.setExecutor(...)
Configures Tomcat to use virtual threads for processing incoming HTTP requests.