What is a Thread Pool and How to Create It in Java

πŸ’‘ Concept: Thread Pool

A thread pool is a managed set of reusable threads used to execute tasks. It improves performance by reusing threads instead of creating new ones for every task.

πŸ“˜ Quick Intro

Thread pools are managed via the Executor framework in Java. They help efficiently manage system resources when running many tasks concurrently.

🧠 Analogy

Imagine a restaurant with a fixed number of waiters. Instead of hiring a new waiter for each customer, the restaurant reuses its existing waiters β€” that’s a thread pool.

πŸ”§ Technical Explanation

  • Java provides Executors like newFixedThreadPool() to create a thread pool.
  • Tasks are submitted using execute() or submit() methods.
  • The pool manages a queue of submitted tasks and runs them using its threads.
  • Thread pool prevents overhead of frequent thread creation and destruction.

🎯 Use Cases

  • βœ… Running multiple tasks in parallel with limited system threads.
  • βœ… Scenarios like web servers, data processing pipelines, and batch jobs.
  • βœ… Helps manage CPU resources and avoid out-of-memory errors due to thread overload.

πŸ’» Example: Creating a Thread Pool


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        for (int i = 1; i <= 5; i++) {
            final int task = i;
            executor.submit(() -> {
                System.out.println("Executing Task " + task + " on " + Thread.currentThread().getName());
            });
        }

        executor.shutdown();
    }
}

❓ Interview Q&A

Q1: What is a thread pool in Java?
A: A collection of worker threads used to execute tasks efficiently.

Q2: Why use a thread pool?
A: To avoid overhead of thread creation and improve system performance.

Q3: Which Java package provides thread pool support?
A: java.util.concurrent.

Q4: What does ExecutorService do?
A: Manages and controls the execution of asynchronous tasks.

Q5: Difference between execute() and submit()?
A: submit() returns a Future; execute() does not.

Q6: How to shutdown a thread pool?
A: Use shutdown() or shutdownNow() methods.

Q7: Can thread pools cause memory leaks?
A: Yes, if tasks hold references and pool isn't shut down properly.

Q8: What is newFixedThreadPool()?
A: Creates a thread pool with a fixed number of threads.

Q9: Can a thread pool have unbounded threads?
A: Yes, using newCachedThreadPool().

Q10: How does a thread pool improve scalability?
A: By reusing threads, reducing context-switching and memory usage.

πŸ“ MCQs

Q1. What is the benefit of using a thread pool?

  • Creates more threads
  • Reuses threads to execute tasks efficiently
  • Prevents CPU usage
  • Blocks IO

Q2. Which class is used to manage a thread pool?

  • Thread
  • Runnable
  • ExecutorService
  • ThreadManager

Q3. Which method shuts down a thread pool?

  • terminate()
  • kill()
  • shutdown()
  • stop()

Q4. What is the key difference between execute() and submit()?

  • submit() runs faster
  • submit() returns a Future
  • execute() runs twice
  • submit() is deprecated

Q5. Which Executor creates a fixed number of threads?

  • newThreadPool()
  • newExecutor()
  • newFixedThreadPool()
  • newWorkerPool()

Q6. What happens when more tasks are submitted than threads in pool?

  • Rejected
  • Lost
  • Wait in queue
  • Run simultaneously

Q7. Can thread pools cause memory leaks?

  • No
  • Yes, if not shut down properly
  • Only in Java 6
  • Only if synchronized

Q8. What does shutdownNow() do?

  • Waits for tasks
  • Restarts pool
  • Attempts to stop all tasks
  • Creates new pool

Q9. What interface does ExecutorService extend?

  • Callable
  • Executor
  • Thread
  • Runnable

Q10. Can we submit Runnable and Callable to thread pool?

  • Only Runnable
  • Only Callable
  • Yes
  • No

πŸ’‘ Bonus Insight

Use ThreadPoolExecutor directly for advanced control like setting queue capacity, core/max pool size, and rejection policies.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ” Navigation

Share:

Tags:


Feedback Modal Popup