javaintermediate

ExecutorService — Thread Pool Management

Create and manage thread pools with ExecutorService: fixed, cached, scheduled, and custom pools.

java
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.