Java

ExecutorService — Thread Pools

admin by @admin ADMIN
Jun 12, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`ExecutorService` is the modern way to manage threads. Submit Callables/Runnables, get Futures back. Always shutdown the executor — and prefer try-with-resources on Java 19+ where ExecutorService is AutoCloseable.
Java
Raw
import java.util.*;
import java.util.concurrent.*;

class Demo {
    void example() throws Exception {
        // Java 19+ — ExecutorService is AutoCloseable
        try (ExecutorService pool = Executors.newFixedThreadPool(4)) {

            // Submit a task that returns a value
            Future<Integer> f = pool.submit(() -> {
                Thread.sleep(100);
                return 42;
            });

            // Fire-and-forget
            pool.submit(() -> System.out.println("background"));

            // invokeAll — submit a batch, wait for all
            List<Callable<Integer>> tasks = List.of(
                () -> { Thread.sleep(100); return 1; },
                () -> { Thread.sleep(100); return 2; },
                () -> { Thread.sleep(100); return 3; }
            );
            List<Future<Integer>> results = pool.invokeAll(tasks);
            for (var r : results) System.out.println(r.get());

            System.out.println("answer: " + f.get(1, TimeUnit.SECONDS));
        }   // pool.close() auto-called — waits for tasks to finish
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.