🏷 Virtual Threads
5 patterns
Topic: Virtual Threads
All Java patterns related to Virtual Threads — java.evolved
Streams
Virtual thread executor
Old
ExecutorService exec =
Executors.newFixedThreadPool(10);
try {
futures = tasks.stream()
.map(t -> exec.submit(t))
.toList();
} finally {
exec.shutdown();
}
Modern
try (var exec = Executors
.newVirtualThreadPerTaskExecutor()) {
var futures = tasks.stream()
.map(exec::submit)
.toList();
}
hover to see modern →
JDK 21+
learn more →
Concurrency
Concurrent HTTP with virtual threads
Old
ExecutorService pool =
Executors.newFixedThreadPool(10);
List<Future<String>> futures =
urls.stream()
.map(u -> pool.submit(
() -> fetchUrl(u)))
.toList();
// manual shutdown, blocking get()
Modern
try (var exec = Executors
.newVirtualThreadPerTaskExecutor()) {
var results = urls.stream()
.map(u -> exec.submit(
() -> client.send(req(u),
ofString()).body()))
.toList().stream()
.map(Future::join).toList();
}
hover to see modern →
JDK 21+
learn more →
Concurrency
Scoped values
Old
static final ThreadLocal<User> CURRENT =
new ThreadLocal<>();
void handle(Request req) {
CURRENT.set(authenticate(req));
try { process(); }
finally { CURRENT.remove(); }
}
Modern
static final ScopedValue<User> CURRENT =
ScopedValue.newInstance();
void handle(Request req) {
ScopedValue.where(CURRENT,
authenticate(req)
).run(this::process);
}
hover to see modern →
JDK 25+
learn more →
Concurrency
Structured concurrency
Old
ExecutorService exec =
Executors.newFixedThreadPool(2);
Future<User> u = exec.submit(this::fetchUser);
Future<Order> o = exec.submit(this::fetchOrder);
try {
return combine(u.get(), o.get());
} finally { exec.shutdown(); }
Modern
try (var scope = new StructuredTaskScope
.ShutdownOnFailure()) {
var u = scope.fork(this::fetchUser);
var o = scope.fork(this::fetchOrder);
scope.join().throwIfFailed();
return combine(u.get(), o.get());
}
hover to see modern →
JDK 25+
learn more →
Concurrency
Virtual threads
Old
Thread thread = new Thread(() -> {
System.out.println("hello");
});
thread.start();
thread.join();
Modern
Thread.startVirtualThread(() -> {
IO.println("hello");
}).join();
hover to see modern →
JDK 21+
learn more →