Part 12 / Topic 7 of 7
Putting it together: a parallel price downloader
Real-world example: a small grocery app needs the price of 8 items from a supplier's price API, and the supplier takes 150 ms to answer each request. This course never calls the real internet (Part 11's rule still applies), so ParallelDownloader starts a local, JDK-only HttpServer on localhost standing in for the supplier, and compares three ways of fetching all 8 prices: one at a time, through a fixed ExecutorService, and through virtual threads capped by a Semaphore.
A Semaphore is a counter of permits: acquire() blocks until a permit is free, release() gives one back. Capping concurrency with one — even when virtual threads are cheap — matters because the thing being protected (a real backend's capacity) is not.
Semaphore limit = new Semaphore(maxAtOnce); // never more than maxAtOnce requests in flight
try (ExecutorService virtualPool = Executors.newVirtualThreadPerTaskExecutor()) {
for (String item : ITEMS) {
futures.add(virtualPool.submit(() -> {
limit.acquire();
try { return fetch(client, baseUrl, item); } finally { limit.release(); }
}));
}
...
}
$ javac ParallelDownloader.java
$ java ParallelDownloader
8 prices, 150 ms each, 4 at a time
Method Seconds Speed-up
Sequential 1.29 1.0x
ExecutorService (4 threads) 0.31 4.2x
Virtual threads + Semaphore 0.31 4.2x
same prices every way: true
first price says: price of rice: Rs. 48.00 per kg
Semaphore(4) kept at most 4 requests in flight: true
(The Seconds and Speed-up columns vary by machine and system load, same as every other timing in this part.)
All three methods fetch the exact same 8 prices — the speed-up comes purely from overlapping the waiting, never from the server answering any single request faster. Capped at 4 requests at a time, both the pool and the virtual-thread version land at roughly a 4x speed-up over sequential, and activeRequests/maxActiveRequests (two AtomicIntegers the local server itself maintains) confirm the Semaphore never let more than 4 requests reach the server at once, even though the virtual-thread pool could otherwise submit all 8 immediately.
Full program: examples/ParallelDownloader.java.
Done here? The practice set for Part 12 — including the solutions — is on the part page.