Concurrency

concurrency3ExecutorsDemo

Path
pkg7concurrency/concurrency3ExecutorsDemo.java
Package
pkg7concurrency
Study order
3
Run
Single-file source launch
Command
java pkg7concurrency/concurrency3ExecutorsDemo.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg7concurrency/concurrency3ExecutorsDemo.java
1package pkg7concurrency;2 3/*4 * concurrency3ExecutorsDemo.java5 * ------------------6 * Thread pools via ExecutorService: submit Callables, get Futures, invokeAll,7 * and shut down cleanly. Prefer pools over manually creating threads.8 *9 * POOL TYPES:10 *   - newFixedThreadPool(n)  : bounded worker pool.11 *   - newCachedThreadPool()  : grows/shrinks on demand.12 *   - newSingleThreadExecutor: serial execution.13 *   - newVirtualThreadPerTaskExecutor() : a virtual thread per task (Java 21).14 */15import java.util.*;16import java.util.concurrent.*;17 18public class concurrency3ExecutorsDemo {19 20    public static void main(String[] args) throws Exception {21        ExecutorService pool = Executors.newFixedThreadPool(4);22 23        // submit a Callable -> get a Future24        Future<Integer> future = pool.submit(() -> {25            Thread.sleep(50);26            return 6 * 7;27        });28        System.out.println("future result: " + future.get());   // blocks until ready29 30        // invokeAll: run many tasks, collect results31        List<Callable<Integer>> tasks = new ArrayList<>();32        for (int i = 1; i <= 5; i++) {33            int n = i;34            tasks.add(() -> n * n);35        }36        List<Future<Integer>> results = pool.invokeAll(tasks);37        List<Integer> squares = new ArrayList<>();38        for (Future<Integer> f : results) squares.add(f.get());39        System.out.println("squares 1..5: " + squares);40 41        // invokeAny: first successful result wins42        Integer any = pool.invokeAny(List.of(() -> 1, () -> 2, () -> 3));43        System.out.println("invokeAny returned one of {1,2,3}: " + any);44 45        // Always shut down the pool46        pool.shutdown();47        boolean done = pool.awaitTermination(2, TimeUnit.SECONDS);48        System.out.println("pool terminated cleanly: " + done);49 50        // Java 21: virtual-thread-per-task executor (great for blocking I/O)51        try (ExecutorService vexec = Executors.newVirtualThreadPerTaskExecutor()) {52            Future<String> f = vexec.submit(() -> "ran on " + Thread.currentThread());53            System.out.println("virtual task: " + f.get());54        }   // try-with-resources closes (and awaits) the executor55    }56}