Thread Pool with ExecutorService
Creates a fixed thread pool to execute multiple tasks concurrently, demonstrating proper resource management with try-with-resources and shutdown handling.
Code
import java.util.concurrent.*;
import java.util.List;
public class ThreadPoolExecutor {
public static void main(String[] args) throws InterruptedException {
try (ExecutorService executor = Executors.newFixedThreadPool(4)) {
List<Callable<String>> tasks = List.of(
() -> { Thread.sleep(500); return "Task 1 done"; },
() -> { Thread.sleep(300); return "Task 2 done"; },
() -> { Thread.sleep(700); return "Task 3 done"; },
() -> { Thread.sleep(200); return "Task 4 done"; }
);
List<Future<String>> futures = executor.invokeAll(tasks);
for (Future<String> future : futures) {
try {
System.out.println(future.get());
} catch (ExecutionException e) {
System.err.println("Task failed: " + e.getCause());
}
}
}
System.out.println("All tasks completed");
}
}What the code does
Thread Pool with ExecutorService is built around the class ThreadPoolExecutor.
Repetition is confined to for (Future<String> future : futures) — the rest of the file is straight-line. No finally block here — resources declared in the try header close themselves in reverse order.
Using it
The demo output is labeled (All tasks completed), so every printed line maps back to its originating operation.
Key statements
() -> { Thread.sleep(200); return "Task 4 done"; }
Interactive Tools for This Topic
FAQ
- What does Thread Pool with ExecutorService print when run?
- Run it as a complete program — the output lines carry labels such as `All tasks completed`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.