Java 23: Virtual Threads, Structured Concurrency, and the Future of High-Throughput Applications
Java 23 brings virtual threads and structured concurrency out of preview, transforming how developers build scalable, low-latency systems. Learn how to migrate and what this means for your architecture.
Why Java 23 Matters Now
Java 23, released in September 2024, marks a turning point for server-side Java development. Two flagship features—virtual threads (now finalized from preview) and structured concurrency (moving toward standardization)—address one of the platform’s oldest pain points: efficient, maintainable concurrent code at scale.
For decades, Java developers have juggled thread pools, callback pyramids, and reactive frameworks to handle thousands of concurrent connections. Virtual threads change that equation entirely. They allow you to write code that looks synchronous—straightforward, readable, debuggable—while running millions of them on a handful of OS threads.
If you’re building microservices, APIs, or high-throughput batch systems, Java 23 gives you a path to significantly lower latency and resource consumption without redesigning your codebase.
Understanding Virtual Threads
The Problem They Solve
Traditional Java threads are expensive. Each OS thread consumes ~2 MB of memory and requires kernel scheduling overhead. Create 10,000 threads for 10,000 concurrent users, and you’re looking at 20 GB just for thread stacks—before your application logic runs.
This forced developers into awkward patterns:
- Thread pools — limit concurrency artificially to manage memory
- Reactive frameworks (Project Reactor, RxJava) — flatten async pipelines, introducing mental overhead
- Callback hell — nested completable futures and lambdas that obscure logic
Virtual threads invert this. They’re lightweight abstractions (100+ bytes, not MB) scheduled by the JVM, not the OS. You can create millions of them. The JVM coordinates them onto a small pool of OS threads, context-switching when one blocks.
How Virtual Threads Work
When a virtual thread encounters a blocking operation (I/O, lock acquisition, Thread.sleep()), it unmounts from the carrier thread (the OS thread running it). The carrier thread picks up another virtual thread to execute. When the blocking operation completes, the virtual thread is remounted onto an available carrier thread.
This happens transparently—your code doesn’t change, but throughput explodes.
// Java 23 — virtual threads make this practical
var threads = IntStream.range(0, 100_000)
.mapToObj(i -> Thread.ofVirtual()
.start(() -> {
try {
// Simulate I/O: fetch from API, database, etc.
Thread.sleep(100);
System.out.println("Task " + i + " completed");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}))
.collect(Collectors.toList());
threads.forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
With platform threads, this would spawn 100,000 OS threads and exhaust memory. With virtual threads, the JVM schedules them efficiently onto, say, 8 carrier threads (one per core).
Key Differences from Platform Threads
| Aspect | Platform Thread | Virtual Thread |
|---|---|---|
| Memory footprint | ~2 MB | ~100 bytes |
| Scheduling | OS kernel | JVM (cooperative) |
| Creation cost | High | Negligible |
| Suitable count | Hundreds to thousands | Millions |
| Blocking I/O | Blocks OS thread | Unmounts; carrier thread continues |
ThreadLocal |
Supported (but expensive at scale) | Supported (lighter) |
Structured Concurrency: Managing Complexity
While virtual threads solve resource scaling, structured concurrency solves complexity at scale. It’s a programming model that treats concurrent tasks as a logical unit with a clear lifecycle.
The Problem: Task Leaks and Cascading Failures
In traditional code, spawning background tasks is fragile:
// Without structured concurrency — risky
var executor = Executors.newFixedThreadPool(10);
var future1 = executor.submit(() -> fetchUserData(userId));
var future2 = executor.submit(() -> fetchOrderData(orderId));
// What if future2 throws? future1 still runs. How do we know when both finish?
// What if we exit the method without waiting? Tasks become orphans.
// Debugging: which pool? Which tasks?
Structured concurrency enforces that all concurrent tasks started within a scope must complete (or be cancelled) before exiting that scope. This prevents leaks and makes code reason-able.
The Solution: StructuredTaskScope
Java 23 brings StructuredTaskScope (from Project Loom) closer to finalization:
// Java 23 — structured concurrency
Record<String, Order> fetchUserAndOrder(long userId, long orderId)
throws InterruptedException {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
// Fork tasks within the scope
var userFuture = scope.fork(() -> fetchUserData(userId));
var orderFuture = scope.fork(() -> fetchOrderData(orderId));
// Join: wait for all to complete or one to fail
scope.join();
// If we reach here, both succeeded (scope.join() threw if any failed)
return new Record<>(userFuture.resultNow(), orderFuture.resultNow());
}
}
private static class Record<A, B> {
A first; B second;
Record(A f, B s) { first = f; second = s; }
}
Key benefits:
- Automatic cleanup — scope ensures all forked tasks terminate before exiting
-
Exception handling —
ShutdownOnFailurecancels remaining tasks if one fails - Deadline support — set a timeout; tasks are interrupted if exceeded
- Debuggability — clear parent-child relationships in stack traces
Real-World Example: API Gateway
Imagine an API that aggregates data from multiple backends:
public record AggregatedResponse(
UserDTO user,
List<OrderDTO> orders,
RecommendationsDTO recommendations
) {}
public AggregatedResponse getAggregatedData(long userId)
throws InterruptedException, ExecutionException {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var userTask = scope.fork(() -> userService.getUser(userId));
var ordersTask = scope.fork(() -> orderService.getOrders(userId));
var recsTask = scope.fork(() -> recommendationService.getRecommendations(userId));
scope.join(); // Block until all complete or one fails
return new AggregatedResponse(
userTask.resultNow(),
ordersTask.resultNow(),
recsTask.resultNow()
);
}
}
If any service times out or throws, the scope cancels the others and propagates the exception. No dangling tasks. No resource leaks.
Migration: From ExecutorService to Virtual Threads
Step 1: Create Virtual Threads Instead of Pooling
Before (traditional approach):
private final ExecutorService executor =
Executors.newFixedThreadPool(100); // Artificial limit
public void processRequest(Request req) {
executor.submit(() -> {
// Handle request
handleRequest(req);
});
}
After (Java 23 with virtual threads):
public void processRequest(Request req) {
Thread.ofVirtual()
.name("req-" + req.id())
.start(() -> handleRequest(req));
}
No pool; no artificial concurrency limits. Each request gets its own virtual thread.
Step 2: Migrate ExecutorService Calls
If you use ExecutorService for background jobs:
Before:
var futures = IntStream.range(0, 1000)
.mapToObj(i -> executor.submit(() -> processItem(i)))
.collect(Collectors.toList());
for (var future : futures) {
future.get(); // Wait for completion
}
After (with structured concurrency):
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
for (int i = 0; i < 1000; i++) {
final int itemId = i;
scope.fork(() -> processItem(itemId));
}
scope.join(); // All tasks complete or fail
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
Step 3: Use Virtual Threads with Reactive Frameworks (Optionally)
You don’t need to abandon Spring WebFlux or Project Reactor. But virtual threads reduce the value proposition of purely async code. Many teams are moving to:
- Spring Boot 3.3+ with virtual threads enabled
- Traditional blocking I/O (JDBC, synchronous HTTP clients)
- Letting the JVM scheduler handle concurrency
This simplifies debugging and testing significantly.
Common Pitfalls and Solutions
Pitfall 1: Assuming Virtual Threads Are Free
Virtual threads are cheap, not free. CPU-bound work (parsing JSON, cryptography, math) doesn’t benefit from virtual threads. The JVM can’t unmount during CPU operations, so millions of CPU-bound virtual threads will still compete for cores.
Solution: Use virtual threads for I/O-bound work. For CPU-bound tasks, stick with platform threads or use appropriate work-stealing pools:
// Good: I/O-bound
var ioThread = Thread.ofVirtual().start(() -> {
var data = httpClient.get("https://api.example.com/data");
processData(data);
});
// Not ideal: CPU-bound
var cpuThread = Thread.ofVirtual().start(() -> {
var hash = sha256(largeData); // CPU-intensive
});
// Better: use a ForkJoinPool or platform thread
Pitfall 2: Pinning to Carrier Threads
If a virtual thread holds a monitor lock (synchronized block) and blocks, it can pin to its carrier thread, preventing other virtual threads from running. This defeats the purpose.
Solution: Use java.util.concurrent locks instead of synchronized:
// Avoid:
public synchronized void criticalSection() {
Thread.sleep(100); // Pins carrier thread!
}
// Prefer:
private final Lock lock = new ReentrantLock();
public void criticalSection() throws InterruptedException {
lock.lock();
try {
Thread.sleep(100); // Doesn't pin
} finally {
lock.unlock();
}
}
Java 23 improves pinning diagnostics, but the best practice is avoiding synchronized when virtual threads block.
Pitfall 3: Forgetting to Handle Interruption
Virtual threads are interrupted when scopes cancel them. If you ignore interruption, tasks won’t respond:
// Bad: ignores interruption
scope.fork(() -> {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// Silently swallowed — task won't exit
}
}
});
// Good: propagate interruption
scope.fork(() -> {
try {
while (true) {
Thread.sleep(10);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore status
return; // Exit
}
});
Performance Impact and Benchmarks
In practical benchmarks (e.g., building a simple REST API handling concurrent requests):
- Throughput: 2-10x improvement with virtual threads (fewer thread context switches, lower memory)
- Latency: p99 latency often decreases by 30-50% (less GC pause time from reduced memory footprint)
- Resource usage: Memory per concurrent request drops from ~1 MB (with platform threads) to ~100 KB
A typical microservice handling 10,000 concurrent users:
| Metric | Platform Threads | Virtual Threads |
|---|---|---|
| Memory (threads alone) | ~20 GB | ~1 GB |
| CPU (context switching) | High | Low |
| Avg request latency | 100 ms | 70 ms |
| p99 latency | 500 ms | 200 ms |
Tools to Test Your Code
When migrating to Java 23, testing concurrent code is critical. Use these Kloubot tools to debug and validate:
- JSON Formatter — if your API responses are JSON, validate structure during integration tests
- API Request Builder — simulate concurrent requests to your Java service and verify response times
- Mock Data Generator — generate realistic test data for load testing virtual thread applications
For unit testing virtual threads, standard JUnit 5 works fine. For integration testing, tools like JCStress can help verify correctness under load.
Getting Started with Java 23
Installation
-
Download Java 23 from Oracle or use a package manager (e.g.,
sdkman install java 23.0.1) -
Verify installation:
java -version # openjdk version "23" 2024-09-17 -
Enable preview features (if needed): Most virtual thread APIs are finalized in Java 23, but structured concurrency is still in preview. Use
--enable-previewduring development:javac --enable-preview Main.java java --enable-preview Main
Framework Support
-
Spring Framework 6.1+ and Spring Boot 3.2+ have excellent virtual thread support. Set
spring.threads.virtual.enabled=trueinapplication.properties. - Quarkus 3.4+ optimized for virtual threads out of the box.
- Micronaut 4.0+ supports virtual threads natively.
- Jakarta EE 11 (released 2024) includes virtual thread support.
A Simple Virtual Thread Example
import java.time.Instant;
import java.util.concurrent.StructuredTaskScope;
public class VirtualThreadDemo {
public static void main(String[] args) throws InterruptedException {
System.out.println("Starting at " + Instant.now());
// Create 1000 virtual threads, each sleeping for 1 second
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
for (int i = 0; i < 1000; i++) {
final int taskId = i;
scope.fork(() -> {
try {
Thread.sleep(1000);
if (taskId < 5) {
System.out.println("Task " + taskId + " completed");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
scope.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
System.out.println("Finished at " + Instant.now());
// With platform threads: ~1000 seconds
// With virtual threads: ~1 second (all run concurrently)
}
}
Compile and run:
javac VirtualThreadDemo.java
java --enable-preview VirtualThreadDemo
Why It Matters for Your Architecture
Java 23’s virtual threads and structured concurrency represent a paradigm shift. For teams building:
- Microservices — handle more requests with fewer resources
- High-frequency traders — lower latency, predictable scheduling
- Real-time systems — better resource utilization, cleaner code
- Legacy monoliths — upgrade gradually; use virtual threads for new features
This is not just a performance optimization; it’s a step toward making Java development more productive and maintainable at scale.
Looking Ahead
In Java 24 (released March 2025) and beyond, expect:
- Scoped values (preview in Java 21, moving toward finalization) — thread-local alternatives for virtual threads
- Foreign Function & Memory API (FFM) — tighter integration with native code
- More reactive framework migration patterns — as virtual threads become the default for I/O
Conclusion
Java 23 delivers on the promise of Project Loom. Virtual threads are production-ready, structured concurrency is stabilizing, and your code becomes simpler and faster. If you’re running Java workloads, upgrading and experimenting with these features is well worth the effort.
Start small: profile your existing application to identify I/O-bound hotspots. Replace thread pools with virtual threads in new code. Test thoroughly. The payoff in latency and resource efficiency is substantial.