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.
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
| Runnable | Callable |
|---|---|
void run() | V call() |
| No result | Returns a result |
| Can't throw checked exceptions | Can throw checked exceptions |
Future — a result that arrives later
Future<Integer> f = pool.submit(() -> 6 * 7);
int answer = f.get(); // waits until ready → 42
CompletableFuture — chain async steps
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.
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
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! 🚀
}
}