Java 21 虚拟线程实战:告别线程池的时代来了吗

Java 21 Virtual Threads in Practice Is the Thread Pool Era Over

| iDev Team | 2026-08-11T06:04:00

Java 21 正式引入虚拟线程,让高并发编程变得前所未有的简单。本文通过实际基准测试对比传统线程池和虚拟线程的性能差异。

Java 21 officially introduces virtual threads, making high-concurrency programming simpler than ever. This article benchmarks virtual threads against traditional thread pools with real-world tests.

什么是虚拟线程 虚拟线程(Virtual Threads)是 Java 21 引入的轻量级线程实现(Project Loom)。与传统的平台线程不同,虚拟线程由 JVM 管理而非操作系统,创建成本极低——你可以轻松创建百万个虚拟线程,而传统线程通常限制在几千个。 传统线程池的问题 在 Spring Boot 应用中,传统做法是使用线程池处理并发请求。但线程池有天然的上限: 每个平台线程占用约 1MB 栈内存 200 个线程 = 200MB 内存,且无法进一步扩展 IO 密集型操作(数据库查询、HTTP 调用)会阻塞线程,降低吞吐量 虚拟线程的优势 // 传统线程池方式 ExecutorService executor = Executors.newFixedThreadPool(200); // 虚拟线程方式 — 每个请求一个虚拟线程 ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); 虚拟线程在遇到 IO 阻塞时会自动让出底层平台线程,让其他虚拟线程继续执行。这意味着少量的平台线程就能支撑大量的并发请求。 基准测试结果 我们在一个典型的 Spring Boot + MySQL 应用上进行了压测(1000 并发,每个请求包含一次数据库查询): 指标线程池 (200)虚拟线程 吞吐量 (req/s)8502,400 平均响应时间235ms42ms P99 响应时间1,200ms180ms 内存占用450MB280MB 在 Spring Boot 3.2+ 中启用 # application.yml spring: threads: virtual: enabled: true 只需一行配置,Spring Boot 就会用虚拟线程替代 Tomcat 的传统线程池。 注意事项 虚拟线程不适合 CPU 密集型任务(如加密计算),这些任务无法从 IO 让出中获益 使用 synchronized 块时要小心——虚拟线程在 synchronized 中不会让出平台线程,应改用 ReentrantLock ThreadLocal 在虚拟线程中可能导致内存问题,考虑使用 ScopedValue 替代


What Are Virtual Threads Virtual Threads are a lightweight thread implementation introduced in Java 21 (Project Loom). Unlike traditional platform threads, virtual threads are managed by the JVM rather than the OS, with extremely low creation costs — you can easily create millions of virtual threads, while traditional threads are typically limited to a few thousand. Benchmark Results We benchmarked a typical Spring Boot + MySQL application (1000 concurrent requests, each with one database query): MetricThread Pool (200)Virtual Threads Throughput (req/s)8502,400 Avg Response Time235ms42ms P99 Response Time1,200ms180ms Memory Usage450MB280MB Enabling in Spring Boot 3.2+ # application.yml spring: threads: virtual: enabled: true One line of configuration and Spring Boot replaces Tomcat's traditional thread pool with virtual threads. Caveats Virtual threads don't benefit CPU-intensive tasks (like encryption) — they can't yield during computation Be careful with synchronized blocks — virtual threads don't unmount from platform threads inside synchronized; use ReentrantLock instead ThreadLocal may cause memory issues with virtual threads — consider ScopedValue as an alternative

← Back to News