Multithreading and Concurrency · Lesson 40 of 42
ExecutorService, CompletableFuture and Virtual Threads
Creating a new Thread for every task doesn't scale – threads are expensive, and managing them by hand is error-prone. Professional Java code hands tasks to an executor and gets results back as futures. Java 21's virtual threads then make it cheap to run thousands of concurrent tasks with simple, blocking-style code – the biggest change to Java concurrency in years.
In this lesson
- Thread pools with
ExecutorService Callable,FutureandinvokeAll- Async pipelines with
CompletableFuture - Virtual threads (Java 21)
A thread pool
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(3); // 3 reusable threads
AtomicInteger sent = new AtomicInteger();
for (int i = 1; i <= 10; i++) {
int id = i;
pool.submit(() -> {
// pretend to send email #id
sent.incrementAndGet();
});
}
pool.shutdown(); // accept no new tasks
pool.awaitTermination(5, TimeUnit.SECONDS); // wait for queued tasks
System.out.println(sent.get() + " emails sent by a pool of 3 threads");
}
}
10 emails sent by a pool of 3 threads
How a fixed thread pool works
- submit(task)the task joins a queue
- Idle worker takes it3 workers run at most 3 tasks at a time
- Worker is reusedno new thread created per task
- shutdown()finish the queue, then stop the workers
Common mistake: forgetting shutdown()
Pool threads are not daemon threads – if you never call shutdown() (or use try-with-resources on the executor, Java 19+), the JVM keeps running after main ends.
Callable and Future: getting results back
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) throws Exception {
try (ExecutorService pool = Executors.newFixedThreadPool(3)) { // closes (and waits) automatically
Callable<Integer> north = () -> 1200 + 450;
Callable<Integer> south = () -> 800 + 1500;
Callable<Integer> east = () -> 990;
Future<Integer> f = pool.submit(north);
System.out.println("north = " + f.get()); // get() waits for the result
List<Future<Integer>> all = pool.invokeAll(List.of(north, south, east));
int total = 0;
for (Future<Integer> r : all) total += r.get();
System.out.println("all regions = " + total);
}
}
}
north = 1650 all regions = 4940
A Runnable returns nothing; a Callable<T> returns a value and may throw a checked exception. Future.get() blocks until the result is ready (pass a timeout in real code).
CompletableFuture: async pipelines
CompletableFuture lets you chain steps that run asynchronously and combine results – for example, loading a user and their orders in parallel:
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Main {
static String fetchUser(int id) { return "user-" + id; }
static List<String> fetchOrders(int id) { return List.of("ORD-1", "ORD-2"); }
public static void main(String[] args) {
CompletableFuture<String> user = CompletableFuture.supplyAsync(() -> fetchUser(7));
CompletableFuture<List<String>> orders = CompletableFuture.supplyAsync(() -> fetchOrders(7));
String page = user.thenCombine(orders, (u, o) -> u + " has " + o.size() + " orders") // both in parallel
.thenApply(String::toUpperCase)
.join();
System.out.println(page);
String safe = CompletableFuture.supplyAsync(() -> { if (true) throw new IllegalStateException("payment service down"); return "ok"; })
.exceptionally(ex -> "fallback: " + ex.getCause().getMessage())
.join();
System.out.println(safe);
}
}
USER-7 HAS 2 ORDERS fallback: payment service down
| Method | Does |
|---|---|
supplyAsync(supplier) | start a task that returns a value |
thenApply(fn) | transform the result |
thenCompose(fn) | chain another async call that depends on the result |
thenCombine(other, fn) | combine two independent results |
allOf(...) | wait for many futures |
exceptionally(fn) / handle(fn) | recover from errors |
Virtual threads (Java 21)
A normal (platform) thread maps to an operating-system thread and costs about a megabyte of memory – a server can afford a few thousand. A virtual thread is managed by the JVM and costs a few hundred bytes, so you can have a million. When a virtual thread blocks (waiting for a database or HTTP call), the JVM parks it and runs another on the same OS thread.
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) {
AtomicInteger done = new AtomicInteger();
long start = System.currentTimeMillis();
try (ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
exec.submit(() -> {
Thread.sleep(Duration.ofMillis(100)); // simulated I/O wait
done.incrementAndGet();
return null;
});
}
} // waits for all tasks
long ms = System.currentTimeMillis() - start;
System.out.println(done.get() + " tasks finished, in well under 10 seconds: " + (ms < 10_000));
}
}
10000 tasks finished, in well under 10 seconds: true
Ten thousand tasks that each wait 100 ms would take 1,000 seconds one after another, or about 5 minutes with a pool of 3 platform threads. With virtual threads they finish in well under a second or two.
When to use what
- Virtual threads – many tasks that spend most time waiting on I/O (web requests, database calls, REST clients). Spring Boot 3.2+ can serve requests on virtual threads with one property.
- Fixed thread pools – CPU-heavy work (image processing, calculations); size ≈ number of CPU cores.
- CompletableFuture – composing several asynchronous steps.
Practice
Try it yourself
Use
CompletableFuture.allOfto fetch three prices in parallel and print their total.Show solution
import java.util.List; import java.util.concurrent.CompletableFuture; public class Main { public static void main(String[] args) { List<CompletableFuture<Integer>> prices = List.of( CompletableFuture.supplyAsync(() -> 499), CompletableFuture.supplyAsync(() -> 1299), CompletableFuture.supplyAsync(() -> 89)); CompletableFuture.allOf(prices.toArray(new CompletableFuture[0])).join(); int total = prices.stream().mapToInt(CompletableFuture::join).sum(); System.out.println(total); } }1887
Quick check
What is the difference between Runnable and Callable?
Callable returns a value and can throw checked exceptions; Runnable returns nothing.
What does Future.get() do?
It waits until the task finishes and returns its result (or throws if the task failed).
What kind of work benefits most from virtual threads?
Large numbers of I/O-bound tasks that spend most of their time waiting.
Summary
- Submit tasks to an ExecutorService instead of creating threads; always shut it down (or use try-with-resources).
- Callable + Future return results; CompletableFuture chains and combines async steps with error handling.
- Java 21 virtual threads make massive I/O concurrency cheap with simple blocking code.
Interview practice: Java multithreading and concurrency questions.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.