← Java roadmap

Topic 16 of 30 · Expert

Executors, CompletableFuture & Virtual Threads

Modern concurrency utilities for real applications.

Concept

ExecutorService manages a thread pool so you submit tasks instead of creating threads. Always shut it down.

Atomic classes (AtomicInteger) and ConcurrentHashMap provide lock-free/fine-grained thread safety. CompletableFuture chains asynchronous steps.

Virtual threads (Java 21) are lightweight threads managed by the JVM — you can run millions of blocking tasks cheaply.

Code (Java 21)

try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
    List<Future<String>> results = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
        int id = i;
        results.add(pool.submit(() -> "task " + id));
    }
    for (var f : results) System.out.println(f.get());
}

CompletableFuture<Integer> price = CompletableFuture
    .supplyAsync(() -> 100)
    .thenApply(p -> p * 2)
    .exceptionally(ex -> 0);
System.out.println(price.join());

Remember

  • Prefer executors over raw threads.
  • ConcurrentHashMap over synchronized HashMap.
  • Virtual threads suit blocking I/O, not CPU-heavy work.

Interview questions

HashMap vs ConcurrentHashMap?

HashMap isn't thread-safe. ConcurrentHashMap allows concurrent reads and fine-grained locked writes, and never throws ConcurrentModificationException.

What are virtual threads?

JVM-managed lightweight threads mapped onto a few carrier OS threads, letting a thread-per-request style scale to huge concurrency.

Practise Java with the AI mentor

Lesson test

Take an 8-question test on “Executors, CompletableFuture & Virtual Threads” — concepts, output prediction, bug spotting and interview questions.

Can't find a Java topic you need for exams or placements? Request it and we'll add it.