[VoxxedDaysTicino2026] Get The Most Out of Virtual Threads in Java 25: A Deep Dive
Lecturer
Christian Wörz is a freelance fullstack developer and Microsoft MVP, with over 14 years crafting code in Java, Kotlin, TypeScript, and JavaScript. He conducts trainings on AI, Java, and web technologies, speaking at conferences on concurrency and modern features.
Abstract
This article appraises Christian Wörz’s live coding session harnessing Java 25’s virtual threads, structured concurrency, and scoped values for concurrent web applications. It scrutinizes enhancements from Java 21, custom task scopes, and thread-local alternatives. Analyzing performance gains, synchronization fixes, and practical integrations, it contemplates scalability in real-world scenarios.
Evolutions in Virtual Threads
Christian elucidates virtual threads’ maturation: Unlike platform threads (1-2MB OS overhead), virtual threads reside in JVM, enabling millions affordably sans pools. Java 25 ameliorates synchronization: Pre-25, synchronized pinned virtual threads to carriers, blocking. Now, uncontended synchronized avoids pinning; contended allows temporary pinning sans full blockage. Contexts: Addresses scalability in I/O-bound apps. Implications: Boosts throughput, reduces latency.
Leveraging Structured Concurrency
StructuredTaskScope (preview) orchestrates subtasks hierarchically, ensuring completion or cancellation together. Christian live-codes a web app: Sequential fetches evolve to concurrent via scopes. Custom joiners (Java 25): Implement Joiner interface for tailored handling—e.g., first successful response. Code:
try (var scope = new StructuredTaskScope<>()) {
var future1 = scope.fork(() -> fetch("url1"));
var future2 = scope.fork(() -> fetch("url2"));
scope.join();
// Process results
}
Implications: Simplifies error propagation, enhances readability.
Scoped Values Over Thread Locals
Scoped values (stable Java 25) supplant thread locals in virtual threads/struct scopes, avoiding inheritance issues. Christian demonstrates: Bind values in runnables, accessible sans inheritance. Code:
private static final ScopedValue<String> USER = ScopedValue.newInstance();
ScopedValue.runWhere(USER, "user1", () -> {
// Access USER.get()
});
Contexts: Mitigates data leakage in concurrent environs. Implications: Promotes immutability, safer sharing.
Practical Applications and Performance
Live iteration builds concurrent server: Virtual threads handle requests, scopes parallelize fetches, scoped values manage contexts. Java 25 fixes ensure efficiency. Implications: Ideal for high-concurrency without reactive complexity. In conclusion, Christian’s techniques optimize Java for modern workloads.