Java · Module 11 · Lesson 21 min read

Executors & Virtual Threads

Thread pools with ExecutorService

Creating a new thread for every task is expensive. A thread pool reuses a fixed set of threads.

Java
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> System.out.println("Task running"));
pool.shutdown();   // finish queued tasks, accept no new ones

Since Java 19, ExecutorService is AutoCloseable, so try-with-resources shuts it down for you.

Runnable vs Callable

RunnableCallable
void run()V call()
No resultReturns a result
Can't throw checked exceptionsCan throw checked exceptions

Future — a result that arrives later

Java
Future<Integer> f = pool.submit(() -> 6 * 7);
int answer = f.get();   // waits until ready → 42

CompletableFuture — chain async steps

Java
CompletableFuture.supplyAsync(() -> fetchUser())
    .thenApply(user -> user.name())
    .thenAccept(System.out::println)
    .exceptionally(e -> { System.out.println("Failed"); return null; });

Thread-safe collections

ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue. Use these instead of plain HashMap/ArrayList when threads share data.

Virtual threads (Java 21) ✨

Virtual threads are super lightweight threads managed by the JVM. You can run millions of them.

Java
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    executor.submit(() -> callApi());
}
Thread.ofVirtual().start(() -> System.out.println("Hi!"));

💡 Perfect for tasks that spend time waiting (web requests, database calls, files). They don't make CPU-heavy maths faster.

Example

Java
import java.util.concurrent.*;
import java.util.stream.IntStream;

public class Downloader {
    static String download(int id) throws InterruptedException {
        Thread.sleep(1000);                  // pretend to wait for the network
        return "file-" + id;
    }

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();

        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            var futures = IntStream.range(0, 10_000)
                .mapToObj(i -> executor.submit(() -> download(i)))
                .toList();
            System.out.println(futures.get(42).get());  // file-42
        }

        System.out.println("Took ~" + (System.currentTimeMillis() - start) + " ms");
        // 10,000 one-second tasks finish in about a second! 🚀
    }
}