Java 21 Virtual Threads: Benefits, Usage, and Performance Comparison
Java 21’s virtual threads provide a lightweight, JVM‑managed alternative to OS threads that enables hundreds of thousands of concurrent tasks, simplifies scheduling, integrates easily into Spring Boot via a preview flag and Tomcat executor, and delivers up to five‑fold speed‑ups and lower latency in high‑load I/O‑intensive applications.
Java 21 introduces virtual threads, a lightweight alternative to OS threads that reduces memory usage and creation overhead, making it ideal for high‑concurrency and I/O‑intensive applications.
Key advantages:
Lightweight – managed by the JVM, allowing creation of hundreds of thousands of threads.
High concurrency support – especially for I/O‑bound workloads.
Automatic scheduling – the JVM adjusts scheduling without manual thread‑pool management.
Basic usage example:
import java.lang.Thread;
Thread virtualThread = Thread.ofVirtual().start(() -> {
System.out.println("虚拟线程正在运行");
});
System.out.println("主线程正在运行");Delayed start example:
import java.lang.Thread;
Thread virtualThread = Thread.ofVirtual()
.name("虚拟线程")
.unstarted(() -> System.out.println("虚拟线程运行中"));
virtualThread.start();
virtualThread.join(); // 等待虚拟线程完成To enable virtual threads in a Spring Boot project, use Java 21 or later and add the --enable-preview flag in pom.xml :
org.apache.maven.plugins
maven-compiler-plugin
21
21
--enable-previewConfigure Tomcat to use a virtual‑thread executor:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executors;
@Configuration
public class VirtualThreadConfig {
@Bean
public TomcatProtocolHandlerCustomizer
protocolHandlerVirtualThreadExecutorCustomizer() {
return protocolHandler -> protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
}
}Performance experiment comparing 100 000 traditional threads vs. virtual threads shows execution time dropping from ~18.6 s to ~3.7 s (≈500 % speed‑up). HTTP request tests (1 600 requests, concurrency 400) also demonstrate lower latency and higher throughput for virtual threads.
Additional Java performance tips include using parallel streams, CompletableFuture for asynchronous I/O, reducing database round‑trips with caching, and employing object pools for resource reuse.
In summary, virtual threads simplify concurrency, dramatically improve performance in high‑load scenarios, and can be adopted with minimal Spring Boot configuration.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
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.