Java

Virtual Threads (Java 21+)

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Java 21's virtual threads are millions-of-them cheap — JVM multiplexes them onto a small carrier pool. Replaces async/reactive code for most I/O-bound workloads: just write blocking code that doesn't actually block a kernel thread.
Java
Raw
import java.net.http.*;
import java.net.URI;
import java.util.*;
import java.util.concurrent.*;

class Demo {
    void example() throws Exception {
        // One-off virtual thread
        Thread.startVirtualThread(() -> System.out.println("from virtual thread"));

        // Virtual-thread-per-task executor — spawns a new VT per submit()
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {

            var client = HttpClient.newHttpClient();
            var urls = List.of(
                "https://example.com",
                "https://example.org",
                "https://example.net"
            );

            // Fire 10,000 of these — costs almost nothing
            var futures = urls.stream().map(url ->
                executor.submit(() -> {
                    var resp = client.send(
                        HttpRequest.newBuilder(URI.create(url)).build(),
                        HttpResponse.BodyHandlers.ofString()
                    );
                    return url + " → " + resp.statusCode();
                })
            ).toList();

            for (var f : futures) System.out.println(f.get());
        }
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.