Summary - Concurrent API
- Java course
- Advanced
- Lesson 66/82
- 5 min
Combine ExecutorService and CompletableFuture to write a parallel downloader.
Summary - Concurrent API
In this group you saw the core tools of java.util.concurrent: a pool with ExecutorService, results with Callable and Future, chains with CompletableFuture, a safe map with ConcurrentHashMap, and flexible locking with Lock.
Now you will combine these into a mini task: building a ParallelSum that runs tasks in parallel.
Practice Sum two tasks in parallel with ParallelSum
Write main in a ParallelSum class; create a pool with Executors.newFixedThreadPool(2). Define two Callable<Integer> tasks: () -> 10 and () -> 20. Submit both; fetch results with get(); sum and print. Call shutdown().
Starter code
import java.util.concurrent.*;
// Write main in ParallelSum
// Create pool with newFixedThreadPool(2); submit two Callables; sum get; shutdownSample solution
import java.util.concurrent.*;
class ParallelSum {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<Integer> a = pool.submit(() -> 10);
Future<Integer> b = pool.submit(() -> 20);
System.out.println(a.get() + b.get());
pool.shutdown();
}
}Expected output
30
Practice A chain with CompletableFuture
Write main in a new ChainDemo class; start with CompletableFuture.supplyAsync(() -> "hi"), transform with .thenApply(s -> s.toUpperCase()) to upper case and print with System.out.println(f.join()).
Starter code
import java.util.concurrent.*;
// Write main in ChainDemo
// Return "hi" with supplyAsync; upper-case with thenApply; print joinSample solution
import java.util.concurrent.*;
class ChainDemo {
public static void main(String[] args) {
CompletableFuture<String> f =
CompletableFuture.supplyAsync(() -> "hi").thenApply(s -> s.toUpperCase());
System.out.println(f.join());
}
}Expected output
HI
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the best method to wait for a task's result?
- Thread.sleep()
- Object.wait()
- Thread.yield()
- Future.get() Correct answer
Explanation: Future.get() waits until the task finishes.
2 Match the Concurrent API summary
| Term | Meaning |
|---|---|
ExecutorService |
Manages a pool |
Future |
Waits for result |
CompletableFuture |
Builds a chain |
Lock |
Flexible lock |