ExecutorService — Thread Pool Management
Create and manage thread pools with ExecutorService: fixed, cached, scheduled, and custom pools.
import java.util.concurrent.*;
import java.util.List;
import java.util.stream.IntStream;
public class ExecutorDemo {
public static void main(String[] args) throws Exception {
// 1. Fixed thread pool
ExecutorService fixed = Executors.newFixedThreadPool(4);
List<Future<String>> futures = IntStream.range(0, 10)
.mapToObj(i -> fixed.submit(() -> {
Thread.sleep(100);
return "Task-" + i + " done by " + Thread.currentThread().getName();
}))
.toList();
for (var f : futures) System.out.println(f.get());
fixed.shutdown();
// 2. Scheduled executor
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
scheduler.scheduleAtFixedRate(
() -> System.out.println("Heartbeat: " + System.currentTimeMillis()),
0, 1, TimeUnit.SECONDS
);
Thread.sleep(3000);
scheduler.shutdown();
// 3. Custom thread pool
ThreadPoolExecutor custom = new ThreadPoolExecutor(
4, // core pool size
8, // max pool size
60, TimeUnit.SECONDS, // idle thread keepalive
new LinkedBlockingQueue<>(100), // work queue
new ThreadPoolExecutor.CallerRunsPolicy() // rejection policy
);
custom.submit(() -> System.out.println("Custom pool task"));
custom.shutdown();
custom.awaitTermination(5, TimeUnit.SECONDS);
}
}Use Cases
- Managing concurrent task execution
- Scheduling periodic background jobs
- Custom thread pool tuning for specific workloads
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
CompletableFuture — Async Programming
Chain async operations with CompletableFuture: thenApply, thenCompose, allOf, and exception handling.
Best for: Parallel API calls to multiple services
Virtual Threads — Lightweight Concurrency
Use Java 21 virtual threads for massive concurrency without thread pool tuning or reactive frameworks.
Best for: High-concurrency web servers handling thousands of requests
Concurrent Collections — Thread-Safe Maps
Use ConcurrentHashMap, CopyOnWriteArrayList, and BlockingQueue for thread-safe data structures.
Best for: Thread-safe caching in multi-threaded applications
Rate Limiter — Token Bucket Algorithm
Implement a thread-safe rate limiter using the token bucket algorithm for API throttling.
Best for: API rate limiting per user or IP