Concurrency: executors, CompletableFuture and virtual threads
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
Why concurrency
Computers have many cores, and programs often wait for networks and disks. Concurrency lets you use both. It is also the area where Java programs fail in the strangest ways, so this lesson stays with the safe, modern tools.
You can create a Thread directly: new Thread(() -> ...).start(). In real code you rarely do that. You submit tasks to an executor, which manages threads for you.
Executors and futures
An ExecutorService accepts tasks and runs them on a pool of threads. Submitting a Callable returns a Future, a handle to a result that will exist later. Since Java 19, ExecutorService is AutoCloseable, so you can use it in try-with-resources, and close() waits for submitted tasks to finish.
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static int plainCounter = 0;
public static void main(String[] args) throws Exception {
// 1. A fixed thread pool with Futures
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
final int n = i;
futures.add(pool.submit(() -> squareSlowly(n)));
}
int total = 0;
for (Future<Integer> f : futures) {
total += f.get(); // blocks until that task is done
}
System.out.println("Sum of squares: " + total);
}
// 2. CompletableFuture: compose asynchronous steps
CompletableFuture<String> user = CompletableFuture.supplyAsync(() -> sleepAndReturn("Ayesha", 200));
CompletableFuture<Integer> orders = CompletableFuture.supplyAsync(() -> {
sleepAndReturn("x", 200);
return 7;
});
String summary = user.thenCombine(orders, (u, o) -> u + " has " + o + " orders").get();
System.out.println(summary);
// 3. Race condition versus atomic counter
AtomicInteger atomic = new AtomicInteger();
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int t = 0; t < 8; t++) {
pool.submit(() -> {
for (int i = 0; i < 10_000; i++) {
plainCounter++; // not thread-safe
atomic.incrementAndGet(); // thread-safe
}
});
}
}
System.out.println("Atomic: " + atomic.get() + " (expected 80000)");
System.out.println("Plain: " + plainCounter + " (usually lower, and different on every run)");
// 4. Virtual threads: thousands of blocking tasks are cheap
Instant start = Instant.now();
ConcurrentHashMap<Integer, String> results = new ConcurrentHashMap<>();
try (ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 5_000; i++) {
final int id = i;
vt.submit(() -> {
Thread.sleep(500); // simulated blocking call
results.put(id, "done");
return id;
});
}
}
long ms = Duration.between(start, Instant.now()).toMillis();
System.out.println(results.size() + " tasks finished; ran in about 1 second, not 40 minutes: " + (ms < 10_000));
// 5. Starting a single virtual thread
Thread thread = Thread.ofVirtual().name("greeter").start(
() -> System.out.println("Hello from a virtual thread: " + Thread.currentThread().isVirtual()));
thread.join();
}
static int squareSlowly(int n) throws InterruptedException {
Thread.sleep(100);
return n * n;
}
static String sleepAndReturn(String value, long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return value;
}
}
Walking through it
The first block creates a pool with four threads and submits five tasks. Each submit returns a Future immediately. We collect them all first and only then call get(), so the tasks run side by side. If we called get() straight after each submit, we would wait for each task before starting the next and lose all the benefit. The try-with-resources makes sure that the pool shuts down.
CompletableFuture adds composition. supplyAsync starts work on a background thread and returns a future. thenCombine waits for two futures and merges their results. The two sleeps happen at the same time, so the whole step takes about 200 milliseconds, not 400. Other useful methods are exceptionally (a fallback if a step fails), thenApply (transform the result), thenCompose (chain another async call) and allOf (wait for several).
Shared state and race conditions
The counter section shows the classic bug. plainCounter++ looks like one step, but it is three: read, add, write. Two threads can read the same value and both write back the same result, so increments get lost. The final value of the plain counter is unpredictable and usually less than 80000. AtomicInteger does the update as a single indivisible operation, and always reaches 80000. For simple counters, use the atomic classes. For maps shared between threads, use ConcurrentHashMap. For larger critical sections, use synchronized blocks or ReentrantLock. The best fix is often to avoid shared mutable state altogether and pass immutable data, such as records, between tasks.
Virtual threads
An ordinary Java thread, called a platform thread, maps one-to-one to an operating system thread. These are heavy. A machine can handle a few thousand at most. That is why thread pools exist, and why server code with one thread per request used to hit a ceiling.
Java 21 made virtual threads a final feature. A virtual thread is managed by the JVM, not the operating system. It is cheap, you can have millions, and when it blocks on I/O or a sleep, the JVM parks it and lets the underlying carrier thread run something else. You write simple blocking code, and you get the scalability that used to require asynchronous callbacks.
In the example, 5000 tasks each sleep half a second. With a pool of 200 platform threads that would take over twelve seconds. With newVirtualThreadPerTaskExecutor, every task gets its own virtual thread and the whole run takes about a second. Notice that you do not pool virtual threads. You create one per task, because they are so cheap that pooling them would only add overhead.
Virtual threads are for tasks that spend their time waiting: HTTP calls, database queries, file I/O. They do not make CPU-heavy code faster, since you still have only as many cores as you have. They also do not remove the need for thread-safe shared state.
Common mistakes
- Calling
Future.get()right after submit, which serialises the work. - Not shutting down an executor. The JVM may never exit. Use try-with-resources.
- Sharing a non-thread-safe object, such as
ArrayList,HashMaporSimpleDateFormat, between threads. - Pooling virtual threads or using them for CPU-bound loops.
Try it yourself
- Replace the
AtomicIntegerwith a normalintguarded by asynchronizedblock, and verify the total is correct. - Use
CompletableFuture.allOfto wait for three simulated service calls and print each result.
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static int plainCounter = 0;
public static void main(String[] args) throws Exception {
// 1. A fixed thread pool with Futures
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
final int n = i;
futures.add(pool.submit(() -> squareSlowly(n)));
}
int total = 0;
for (Future<Integer> f : futures) {
total += f.get(); // blocks until that task is done
}
System.out.println("Sum of squares: " + total);
}
// 2. CompletableFuture: compose asynchronous steps
CompletableFuture<String> user = CompletableFuture.supplyAsync(() -> sleepAndReturn("Ayesha", 200));
CompletableFuture<Integer> orders = CompletableFuture.supplyAsync(() -> {
sleepAndReturn("x", 200);
return 7;
});
String summary = user.thenCombine(orders, (u, o) -> u + " has " + o + " orders").get();
System.out.println(summary);
// 3. Race condition versus atomic counter
AtomicInteger atomic = new AtomicInteger();
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int t = 0; t < 8; t++) {
pool.submit(() -> {
for (int i = 0; i < 10_000; i++) {
plainCounter++; // not thread-safe
atomic.incrementAndGet(); // thread-safe
}
});
}
}
System.out.println("Atomic: " + atomic.get() + " (expected 80000)");
System.out.println("Plain: " + plainCounter + " (usually lower, and different on every run)");
// 4. Virtual threads: thousands of blocking tasks are cheap
Instant start = Instant.now();
ConcurrentHashMap<Integer, String> results = new ConcurrentHashMap<>();
try (ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 5_000; i++) {
final int id = i;
vt.submit(() -> {
Thread.sleep(500); // simulated blocking call
results.put(id, "done");
return id;
});
}
}
long ms = Duration.between(start, Instant.now()).toMillis();
System.out.println(results.size() + " tasks finished; ran in about 1 second, not 40 minutes: " + (ms < 10_000));
// 5. Starting a single virtual thread
Thread thread = Thread.ofVirtual().name("greeter").start(
() -> System.out.println("Hello from a virtual thread: " + Thread.currentThread().isVirtual()));
thread.join();
}
static int squareSlowly(int n) throws InterruptedException {
Thread.sleep(100);
return n * n;
}
static String sleepAndReturn(String value, long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return value;
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account