Using Java 21 Virtual Threads in Spring Boot: Basics, Performance Comparison, and Best Practices
This article introduces Java 21 virtual threads, explains their lightweight and high‑concurrency advantages, demonstrates basic and delayed creation, shows how to enable them in Spring Boot with minimal configuration, compares performance against traditional threads, and provides additional Java performance optimization tips.
Virtual threads, introduced in Java 21, are lightweight JVM‑managed threads that greatly reduce memory and creation cost, enabling creation of hundreds of thousands of threads.
Key advantages: lightweight, high concurrency for I/O‑bound workloads, and automatic scheduling without manual thread‑pool management.
Basic usage example:
Thread virtualThread = Thread.ofVirtual().start(() -> {
System.out.println("虚拟线程正在运行");
});
System.out.println("主线程正在运行");Delayed start example:
Thread virtualThread = Thread.ofVirtual()
.name("虚拟线程")
.unstarted(() -> System.out.println("虚拟线程运行中"));
virtualThread.start();
virtualThread.join(); // 等待虚拟线程完成To use virtual threads in a Spring Boot project, set the Java version to 21, enable preview features in pom.xml , configure monitoring in application.properties , and replace Tomcat’s executor with a virtual‑thread executor:
@Bean
public TomcatProtocolHandlerCustomizer
protocolHandlerVirtualThreadExecutorCustomizer() {
return protocolHandler -> protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
}Performance experiments show creating 100 000 traditional threads takes about 18.6 s, while the same number of virtual threads finishes in 3.7 s (≈500 % speedup). In an HTTP benchmark (1600 requests, 400 concurrency) virtual threads achieve 7.9 s total time and 202 req/s versus 9.66 s and 166 req/s for traditional threads.
Additional Java performance tips include using parallel streams for CPU‑bound tasks, CompletableFuture for asynchronous I/O, reducing database round‑trips with caching, and employing object pools such as Apache Commons Pool to improve memory efficiency.
In summary, Java virtual threads simplify concurrent programming, dramatically improve throughput in high‑concurrency scenarios, and can be enabled in Spring Boot with minimal code changes, while other optimizations further boost application performance.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.