Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What are Thread Pools and ExecutorService? How do they improve performance? Thread Pools और ExecutorService क्या हैं? Performance कैसे improve करते हैं?

Answer

Thread pools manage a pool of reusable threads, eliminating overhead of creating/destroying threads. ExecutorService provides high-level API for asynchronous task execution and thread management.

import java.util.concurrent.*;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        // Create thread pool with 5 threads
        ExecutorService executor = Executors.newFixedThreadPool(5);
        
        // Submit tasks
        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            executor.submit(() -> {
                System.out.println('Task ' + taskId + ' running on ' + 
                    Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {}
            });
        }
        
        // Shutdown executor
        executor.shutdown();  // No new tasks accepted
        
        try {
            // Wait for all tasks to complete
            executor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println('All tasks completed');
    }
}

// Different ExecutorService types:

// 1. FixedThreadPool - fixed number of threads
ExecutorService fixed = Executors.newFixedThreadPool(5);

// 2. CachedThreadPool - dynamic threads (reuse when idle)
ExecutorService cached = Executors.newCachedThreadPool();

// 3. SingleThreadExecutor - single thread (sequential execution)
ExecutorService single = Executors.newSingleThreadExecutor();

// 4. ScheduledThreadPool - scheduled tasks
ScheduledExecutorService scheduled = 
    Executors.newScheduledThreadPool(5);
scheduled.schedule(() -> System.out.println('Task'), 5, TimeUnit.SECONDS);

// 5. Custom ThreadPoolExecutor
ThreadPoolExecutor custom = new ThreadPoolExecutor(
    5,              // Core threads
    10,             // Max threads
    60,             // Keep-alive time
    TimeUnit.SECONDS,
    new LinkedBlockingQueue<>()  // Task queue
);

// Return values from tasks
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<Integer> future = executor.submit(() -> {
    Thread.sleep(2000);
    return 42;
});

try {
    Integer result = future.get();  // Blocks until result
    System.out.println('Result: ' + result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}

executor.shutdown();

// Advantages over manual threading:
// 1. Thread reuse - eliminates creation overhead
// 2. Bounded resources - max threads controlled
// 3. Queue management - automatic task queuing
// 4. Automatic cleanup - shutdown management
// 5. Better performance - especially for many tasks
Thread Pools:

Laभ:
1. Thread reuse - creation cost नहीं
2. Resource control - bounded threads
3. Task queuing - automatic management
4. Performance - 100x faster than manual

ExecutorService Types:

1. FixedThreadPool(5):
   - 5 threads constant
   - Long-running tasks के लिए

2. CachedThreadPool():
   - Dynamic threads
   - Short tasks के लिए

3. SingleThreadExecutor():
   - One thread only
   - Sequential execution

4. ScheduledThreadPool(5):
   - Scheduled tasks
   - Delay/repeat के लिए

Usage:
ExecutorService executor = 
  Executors.newFixedThreadPool(5);
executor.submit(() -> { });
executor.shutdown();

Was this answer clear?