Thread Pool Design Pattern

Back To Index

Overview

The Thread Pool Design Pattern is a concurrency pattern that maintains a pool of threads to perform tasks, reusing existing threads instead of creating new ones. This helps manage system resources efficiently and improves application performance.

Key Characteristics

Implementation

The following is an example of a Thread Pool implementation in Java:


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

class Task implements Runnable {
    private final String name;

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

    @Override
    public void run() {
        System.out.println("Task " + name + " is being executed by " + Thread.currentThread().getName());
        try {
            Thread.sleep(2000); // Simulate task execution time
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Task " + name + " is finished.");
    }
}

public class ThreadPoolDemo {
    public static void main(String[] args) {
        // Create a thread pool with 3 threads
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // Submit tasks to the thread pool
        for (int i = 1; i <= 5; i++) {
            Task task = new Task("Task-" + i);
            executorService.submit(task);
        }

        // Shutdown the thread pool
        executorService.shutdown();
    }
}
    

When to Use

Advantages

Disadvantages

Back To Index