Understanding Java Virtual Threads: Basics, Spring Boot Integration, and Performance Comparison
This article introduces Java 21's virtual threads, explains their lightweight and high‑concurrency advantages, demonstrates basic usage and Spring Boot integration with code examples, and compares their performance against traditional threads through practical experiments and additional optimization tips.
Virtual threads, introduced in Java 21, simplify concurrent programming by being managed by the JVM instead of the operating system, offering lightweight memory usage, the ability to create hundreds of thousands of threads, high concurrency for I/O‑intensive workloads, and automatic scheduling without manual thread‑pool management.
Basic Usage of Virtual Threads
Creating a virtual thread is straightforward; it can be started similarly to a traditional thread but with far lower overhead:
Thread virtualThread = Thread.ofVirtual().start(() -> {
System.out.println("虚拟线程正在运行");
});
System.out.println("主线程正在运行");Virtual threads can also be created in an unstarted state and started later:
Thread virtualThread = Thread.ofVirtual()
.name("虚拟线程")
.unstarted(() -> System.out.println("虚拟线程运行中"));
virtualThread.start();
virtualThread.join(); // 等待虚拟线程完成Using Virtual Threads in Spring Boot
To enable virtual threads in a Spring Boot project, ensure Java 21+ is used, add the --enable-preview flag in pom.xml , and configure the Tomcat executor to use a virtual‑thread per‑task executor:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>21</source>
<target>21</target>
<compilerArgs>
<arg>--enable-preview</arg>
</compilerArgs>
</configuration>
</plugin>Enable monitoring in application.properties and customize Tomcat to use virtual threads:
management.endpoints.web.exposure.include=health,info,metrics @Bean
public TomcatProtocolHandlerCustomizer
protocolHandlerVirtualThreadExecutorCustomizer() {
return protocolHandler -> protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
}Experiment: Traditional Threads vs. Virtual Threads
1. Creating 100,000 Threads
Traditional threads took about 18.6 seconds:
for (int i = 0; i < 100_000; i++) {
Thread thread = new Thread(() -> System.out.println(i));
thread.start();
thread.join();
}Virtual threads completed the same work in roughly 3.7 seconds, a performance gain of nearly 500%.
for (int i = 0; i < 100_000; i++) {
Thread thread = Thread.ofVirtual().unstarted(() -> System.out.println(i));
thread.start();
thread.join();
}2. HTTP Request Performance
In a high‑concurrency test (1600 requests, 400 concurrent), traditional threads required 9.659 seconds (165.65 req/s) while virtual threads finished in 7.912 seconds (202.22 req/s), demonstrating significantly higher throughput and lower latency.
Other Java Performance Optimization Techniques
Parallel Streams: Use parallelStream() for CPU‑bound tasks to leverage multiple cores.
List
numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.parallelStream().forEach(number -> {
System.out.println(number * 2);
});Asynchronous Programming with CompletableFuture: Apply CompletableFuture for I/O‑intensive work to avoid blocking threads.
CompletableFuture
future = CompletableFuture.runAsync(() -> {
// 异步执行任务
System.out.println("异步任务完成");
});
future.join(); // 等待任务完成Database Query Optimization: Reduce query count and use caching solutions such as Redis.
Memory Management: Employ object pools (e.g., Apache Commons Pool) to minimize frequent object creation and garbage collection overhead.
Conclusion
Virtual threads revolutionize Java concurrency by simplifying thread management and dramatically improving performance in high‑concurrency scenarios.
They enable the creation of hundreds of thousands of threads without degrading application responsiveness.
Integrating virtual threads into Spring Boot requires only a few configuration steps and yields noticeable speedups.
Additional optimizations—parallel streams, CompletableFuture, query caching, and object pooling—further enhance Java application performance.
By applying these techniques, Spring Boot applications can achieve stronger performance and lower latency under heavy load.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.