Understanding Java Virtual Threads and Their Performance Benefits in Spring Boot
This article introduces Java 21's virtual threads, explains their lightweight and high‑concurrency advantages, demonstrates basic and delayed usage with code examples, shows how to enable them in Spring Boot, compares performance against traditional threads, and offers additional Java performance‑tuning techniques.
Virtual threads, introduced in Java 21, are a lightweight alternative to traditional OS‑managed threads, offering lower memory overhead, higher concurrency for I/O‑bound workloads, and automatic scheduling by the JVM.
Lightweight : Managed by the JVM, allowing creation of hundreds of thousands of threads with minimal cost.
High Concurrency : Ideal for I/O‑intensive applications, enabling responsive, high‑throughput services.
Automatic Management : No need to manually manage thread pools; the JVM adjusts scheduling based on load.
Basic Usage of Virtual Threads
Creating and starting a virtual thread is as simple as:
Thread virtualThread = Thread.ofVirtual().start(() -> {
System.out.println("虚拟线程正在运行");
});
System.out.println("主线程正在运行");Delayed Start
You can create an unstarted virtual thread, name it, and start it later:
Thread virtualThread = Thread.ofVirtual()
.name("虚拟线程")
.unstarted(() -> System.out.println("虚拟线程运行中"));
virtualThread.start();
virtualThread.join(); // wait for completionUsing Virtual Threads in Spring Boot
To enable virtual threads in a Spring Boot project, ensure you are using Java 21 or newer and enable preview features in pom.xml :
<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 metrics exposure in application.properties :
management.endpoints.web.exposure.include=health,info,metricsConfigure Tomcat to use a virtual‑thread executor:
@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 to complete, while virtual threads finished in 3.7 seconds , a performance gain of roughly 500%.
2. HTTP Request Performance
In a test of 1,600 HTTP requests with 400 concurrent users, traditional threads required 9.659 seconds (165.65 req/s) whereas virtual threads needed only 7.912 seconds (202.22 req/s), demonstrating higher throughput and lower latency.
Other Java Performance‑Boosting Techniques
Parallel Streams : Use parallelStream() for CPU‑bound tasks. List numbers = Arrays.asList(1, 2, 3, 4, 5); numbers.parallelStream().forEach(number -> { System.out.println(number * 2); });
Asynchronous Programming with CompletableFuture : CompletableFuture future = CompletableFuture.runAsync(() -> { // async task System.out.println("异步任务完成"); }); future.join(); // wait for completion
Database Query Optimization : Reduce query count and use caching (e.g., Redis) to minimize I/O.
Memory Management : Employ object pools such as Apache Commons Pool to reuse resources and lower GC pressure.
Conclusion
Virtual threads revolutionize Java concurrency by simplifying thread management and delivering substantial performance improvements in high‑concurrency scenarios. They can be easily enabled in Spring Boot with a few configuration steps, and when combined with other optimizations like parallel streams, CompletableFuture, and query caching, they help Java applications achieve superior throughput and lower latency.
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.