Tech Interview RoomStudy guides

Java 21

Java 21: Run 1,000 blocking I/O tasks concurrently. Compare sequential, thread pools, CompletableFuture and virtual threads.

Advanced · 2 min read · Lesson 2 of 8 in Java 21

Problem

A service must call a slow dependency (about 50 ms per call, mostly waiting on the network) for 1,000 items. How do you finish quickly without exhausting threads? This is the headline Java 21 feature (JEP 444).

java
import java.util.concurrent.ThreadLocalRandom;

final class SlowIo {
    // Simulates a blocking network call: the thread waits, it does not compute
    static int call(int id) {
        try { Thread.sleep(50); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        return id % 7;
    }
    static long ms(long startNanos) { return (System.nanoTime() - startNanos) / 1_000_000; }
}

Approach 1: Sequential (feasible for a handful of calls)

Total time = n × 50 ms. For 1,000 tasks that is 50 seconds, so the demo runs only 20.

java
class IoSequential {
    static long run(int n) {
        long sum = 0;
        for (int i = 0; i < n; i++) sum += SlowIo.call(i);
        return sum;
    }
}

Approach 2: Fixed platform-thread pool (Java 5)

Concurrency is capped by the pool size: with 100 threads, 1,000 tasks take about 10 rounds × 50 ms = 500 ms. Each platform thread costs about 1 MB of stack and an OS thread, so you cannot simply make the pool 10,000 threads.

java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class IoFixedPool {
    static long run(int n, int threads) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(threads);
        try {
            List<Future<Integer>> futures = new ArrayList<>();
            for (int i = 0; i < n; i++) { int id = i; futures.add(pool.submit(() -> SlowIo.call(id))); }
            long sum = 0;
            for (Future<Integer> f : futures) sum += f.get();
            return sum;
        } finally {
            pool.shutdown();
        }
    }
}

Approach 3: CompletableFuture on the same pool (Java 8)

Nicer composition, but the same limit: the work still blocks pool threads.

java
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

class IoCompletable {
    static long run(int n, int threads) {
        ExecutorService pool = Executors.newFixedThreadPool(threads);
        try {
            List<CompletableFuture<Integer>> all = IntStream.range(0, n)
                .mapToObj(i -> CompletableFuture.supplyAsync(() -> SlowIo.call(i), pool)).toList();
            return all.stream().mapToLong(CompletableFuture::join).sum();
        } finally {
            pool.shutdown();
        }
    }
}

Approach 4: Virtual threads, one per task (Java 21)

A virtual thread is cheap (a few hundred bytes to a few KB, created in about a microsecond). When it blocks in sleep, socket I/O or a BlockingQueue, the JVM unmounts it and the carrier thread runs another one. All 1,000 calls wait at the same time, so the total is roughly one call's latency. ExecutorService is AutoCloseable since Java 19: close() waits for all tasks.

java
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.IntStream;

class IoVirtual {
    static long run(int n) throws Exception {
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<Integer>> futures = IntStream.range(0, n)
                .mapToObj(i -> executor.submit(() -> SlowIo.call(i))).toList();
            long sum = 0;
            for (Future<Integer> f : futures) sum += f.get();     // blocking get is fine on virtual threads
            return sum;
        }
    }

    // Other ways to start virtual threads
    static void otherStyles() throws InterruptedException {
        Thread t1 = Thread.ofVirtual().name("worker-", 0).start(() -> SlowIo.call(1));
        Thread t2 = Thread.startVirtualThread(() -> SlowIo.call(2));
        t1.join();
        t2.join();
    }
}

Approach 5: Virtual threads + a Semaphore to protect the downstream (production answer)

Virtual threads remove the thread limit, not the dependency's limit. If the partner allows 100 concurrent calls (or your DB pool has 20 connections), bound concurrency with a Semaphore. Never pool virtual threads to limit concurrency.

java
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

class IoVirtualBounded {
    static long run(int n, int maxConcurrent) throws Exception {
        Semaphore permits = new Semaphore(maxConcurrent);
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<Integer>> futures = IntStream.range(0, n).mapToObj(i -> executor.submit(() -> {
                permits.acquire();                     // virtual thread parks cheaply while waiting
                try { return SlowIo.call(i); } finally { permits.release(); }
            })).toList();
            long sum = 0;
            for (Future<Integer> f : futures) sum += f.get();
            return sum;
        }
    }
}

class IoDemo {
    public static void main(String[] args) throws Exception {
        long t = System.nanoTime();
        System.out.println("sequential (20 tasks): " + IoSequential.run(20) + " in " + SlowIo.ms(t) + " ms");    // ~1000 ms
        t = System.nanoTime();
        System.out.println("fixed pool 100:        " + IoFixedPool.run(1000, 100) + " in " + SlowIo.ms(t) + " ms");   // ~500 ms
        t = System.nanoTime();
        System.out.println("CompletableFuture 100: " + IoCompletable.run(1000, 100) + " in " + SlowIo.ms(t) + " ms");
        t = System.nanoTime();
        System.out.println("virtual threads:       " + IoVirtual.run(1000) + " in " + SlowIo.ms(t) + " ms");          // ~60-100 ms
        t = System.nanoTime();
        System.out.println("virtual + max 250:     " + IoVirtualBounded.run(1000, 250) + " in " + SlowIo.ms(t) + " ms"); // ~200 ms
        IoVirtual.otherStyles();
    }
}

Feasible → optimal

  1. Sequential: O(n) latency; only for tiny n.
  2. Fixed pool / CompletableFuture: latency ≈ n / poolSize × call time; memory grows with pool size.
  3. Virtual threads: latency ≈ one call; simple blocking code; scales to hundreds of thousands of tasks.
  4. Virtual threads + Semaphore: the production pattern: maximum useful concurrency without overloading dependencies. Virtual threads give no speed-up for CPU-bound work, which is still limited by the number of cores.

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you enable virtual threads in Spring Boot?

On Spring Boot 3.2+ with Java 21, set spring.threads.virtual.enabled=true. Tomcat (or Jetty) then handles each request on a virtual thread, and @Async, @Scheduled, Kafka and RabbitMQ listeners use virtual-thread executors too. Keep the HikariCP pool sized for the database, because the database is now the limit, and check libraries for pinning on Java 21.

What is pinning, and did Java 24 change it?

On Java 21, a virtual thread that blocks while inside a synchronized block (or a native call) cannot unmount, so it pins its carrier thread; a few pinned threads can stall the whole carrier pool. Diagnose with -Djdk.tracePinnedThreads=full or JFR's jdk.VirtualThreadPinned event, and prefer ReentrantLock around blocking calls. JDK 24 (JEP 491) lets virtual threads unmount inside synchronized, removing most pinning; native frames still pin.