SrcForge

Lesson 47

Thread Pool

A thread pool reuses worker threads to execute tasks efficiently without creating new threads each time.

Java Track

Save progress as you learn.

61 lessons

Lesson content

A thread pool is a group of pre-created threads that execute tasks without creating a new thread for every task.

Definition List

  • Thread Pool: A collection of reusable worker threads for executing tasks.
  • Worker Thread: A thread inside the pool that performs assigned tasks.
  • Executor Framework: A Java framework that simplifies thread management.
  • ExecutorService: An interface that manages thread pools and task execution.
  • Task: A unit of work executed by a worker thread.

Thread Pool Types

// Fixed number of threads
ExecutorService executor = Executors.newFixedThreadPool(3);

// Creates threads as needed; reuses idle ones
ExecutorService executor = Executors.newCachedThreadPool();

// Single worker thread only
ExecutorService executor = Executors.newSingleThreadExecutor();

// Delayed or periodic task execution
ExecutorService executor = Executors.newScheduledThreadPool(2);

Thread Pool Workflow

Task Submission

ExecutorService

Thread Pool

Available Worker Thread

Task Execution

Thread Returns to Pool

Example: Java Thread Pool Using ExecutorService

package com.java.Multi_threading;

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

public class ThreadPoolExample {

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(3);

        for (int i = 1; i <= 5; i++) {
            Runnable task = new Task("Task " + i);
            executorService.submit(task);
        }

        executorService.shutdown();
    }
}

class Task implements Runnable {

    private String taskName;

    public Task(String taskName) {
        this.taskName = taskName;
    }

    @Override
    public void run() {
        System.out.println("Executing " + taskName + " on Thread: " + Thread.currentThread().getName());
    }
}

Output

Executing Task 1 on Thread: pool-1-thread-1
Executing Task 2 on Thread: pool-1-thread-2
Executing Task 3 on Thread: pool-1-thread-3
Executing Task 4 on Thread: pool-1-thread-1
Executing Task 5 on Thread: pool-1-thread-2

ExecutorService Methods

// Submit a task for execution
executorService.submit(task);

// Execute without returning a result
executorService.execute(task);

// Stop accepting new tasks; finish existing ones
executorService.shutdown();

// Attempt to stop all tasks immediately
executorService.shutdownNow();

// Check if pool has been shut down
executorService.isShutdown();

Best Practices

  • Always call shutdown() when tasks are complete.
  • Choose the right pool size for your workload.
  • Reuse thread pools instead of creating new ones repeatedly.
  • Handle exceptions inside tasks to avoid silent failures.
  • Prefer ExecutorService over manual thread creation.

FAQ

1. What is a thread pool in Java?

A collection of reusable worker threads that execute tasks without creating a new thread for each one.

2. Why are thread pools faster than manual threads?

Thread pools reuse existing threads, eliminating repeated creation and destruction overhead.

3. What is ExecutorService in Java?

An interface in the Executor Framework that manages thread pools and controls task execution.

Thread pools reuse threads instead of creating new ones.
ExecutorService manages pools and task submission.
Four pool types: fixed, cached, single, scheduled.
Always call shutdown() after submitting tasks.
submit() vs execute(): with vs without return value.
Thread returns to pool after each task completes.
Use Executor Framework over manual thread creation.

Where Java is used

Java in real-world development

Thread Pool

A group of reusable worker threads that execute tasks efficiently.

newFixedThreadPool(n)

Creates a pool with a fixed number of worker threads.

newCachedThreadPool()

Creates threads as needed and reuses idle ones automatically.

submit()

Submits a task to the pool for execution; returns a Future.

shutdown()

Stops new tasks from being accepted; existing tasks complete normally.

ExecutorService

Interface for managing thread pools, task submission and lifecycle.