On this page
Tutorial: Virtual Threads & Concurrent HTTP Client
Prev: Modern Data Modeling | Up: Tutorials | Next: Stream Pipelines & File Processing
Rel: java.util.concurrent, java.net.http, try-with-resources, java.time
Ref: OpenJDK JEP 444 — Virtual Threads , Java 21 API — java.net.http
Tags: #public #java #tutorial #concurrency #http #tier/core
Goal
Fetch multiple URLs concurrently using Java 21 virtual threads (Executors.newVirtualThreadPerTaskExecutor()) and the built-in java.net.http.HttpClient, writing straightforward blocking code that scales without callback pyramids.
Run It Directly
Save as ConcurrentFetchDemo.java and run with OpenJDK 21+:
java ConcurrentFetchDemo.java
Complete Pure-JDK Example
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ConcurrentFetchDemo {
record FetchSummary(URI uri, int status, int bodyBytes, long elapsedMs) {}
static FetchSummary fetchOne(HttpClient client, URI uri) throws Exception {
long start = System.nanoTime();
HttpRequest request = HttpRequest.newBuilder(uri)
.timeout(Duration.ofSeconds(5))
.GET()
.build();
// Blocking call parks only the lightweight virtual thread, not the OS carrier thread
HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
return new FetchSummary(uri, response.statusCode(), response.body().length, elapsedMs);
}
public static void main(String[] args) throws Exception {
List<URI> targets = List.of(
URI.create("https://openjdk.org/"),
URI.create("https://dev.java/"),
URI.create("https://docs.oracle.com/en/java/javase/21/docs/api/")
);
try (HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
var executor = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<FetchSummary>> futures = targets.stream()
.map(uri -> executor.submit(() -> fetchOne(client, uri)))
.toList();
for (Future<FetchSummary> future : futures) {
FetchSummary s = future.get();
System.out.printf("%d | %7d bytes | %4d ms | %s%n",
s.status(), s.bodyBytes(), s.elapsedMs(), s.uri());
}
}
}
}
Key Takeaways
- No thread-pool sizing guesswork: Virtual threads are cheap enough to spawn one per task; do not pool them.
- Deterministic shutdown: Both
HttpClientandExecutorServiceimplementAutoCloseablein Java 21, sotry-with-resourceswaits for submitted tasks and cleans up sockets automatically. - Rate-limit with
Semaphore: If you need to cap concurrency against a downstream API, acquire ajava.util.concurrent.Semaphorepermit inside each virtual thread rather than using a fixed thread pool.
Linked from
Related notes
- tuts/java/tutorials/modern_data_modeling_records_and_sealed Linked here; links to this page; shared tags: #java, #tier, #tutorial
- tuts/java/tutorials/stream_pipelines_and_file_processing Linked here; links to this page; shared tags: #java, #tier, #tutorial
- tuts/java/tutorials Linked here; links to this page; shared tags: #java
- tuts/java/builtins/try_with_resources Linked here; shared tags: #java, #tier
- tuts/java/stdlib/java_net_http Linked here; shared tags: #java
- tuts/java/stdlib/java_time Linked here; shared tags: #java
- tuts/java/stdlib/java_util_concurrent Linked here; shared tags: #java
- tuts/cpp/tutorials/jthread_work_queue_and_atomics shared tags: #concurrency, #tier, #tutorial
- tuts/cpp/stdlib/concurrency/atomic shared tags: #concurrency, #tier
- tuts/cpp/stdlib/concurrency/jthread shared tags: #concurrency, #tier