1. Fixed Thread Pool

Technical Explanation

  • Mechanism: Predefined number of threads
  • Thread Reuse: Threads are reused for multiple tasks
  • Queue Management: Tasks wait in a queue if all threads are busy
  • Best For: Predictable, consistent workloads

// Create a fixed thread pool with 5 threads
ExecutorService executor = Executors.newFixedThreadPool(5);

// Submit tasks to the thread pool
for (int i = 0; i < 10; i++) {
    final int taskId = i;
    executor.submit(() -> {
        System.out.println("Task " + taskId + 
            " executed by " + Thread.currentThread().getName());
    });
}

// Shutdown the executor when done
executor.shutdown();
                                        

2. Cached Thread Pool

Technical Explanation

  • Mechanism: Dynamically create and reuse threads
  • Scalability: Grows and shrinks based on demand
  • Thread Lifecycle: Idle threads kept alive for reuse
  • Best For: Many short-lived, asynchronous tasks

// Create a cached thread pool
ExecutorService executor = Executors.newCachedThreadPool();

// Submit multiple tasks
for (int i = 0; i < 10; i++) {
    final int taskId = i;
    executor.submit(() -> {
        System.out.println("Task " + taskId + 
            " executed by " + Thread.currentThread().getName());
        try {
            Thread.sleep(100); // Simulate work
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    });
}

// Shutdown the executor
executor.shutdown();
                                        

3. Scheduled Thread Pool

Technical Explanation

  • Mechanism: Support for scheduled and periodic tasks
  • Task Scheduling: Delayed and recurring executions
  • Precision: Configurable thread count
  • Best For: Background jobs, monitoring tasks

// Create a scheduled thread pool with 3 threads
ScheduledExecutorService scheduler = 
    Executors.newScheduledThreadPool(3);

// Schedule a task to run after 2 seconds
scheduler.schedule(() -> {
    System.out.println("Delayed task executed");
}, 2, TimeUnit.SECONDS);

// Schedule a task to run every 5 seconds
scheduler.scheduleAtFixedRate(() -> {
    System.out.println("Periodic task executed");
}, 0, 5, TimeUnit.SECONDS);