Skip to content

Implement Thread-Pool Executor pattern #3271

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@
<module>table-module</module>
<module>template-method</module>
<module>templateview</module>
<module>thread-pool-executor</module>
<module>throttling</module>
<module>tolerant-reader</module>
<module>trampoline</module>
Expand Down
200 changes: 200 additions & 0 deletions thread-pool-executor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
---
title: "Thread-Pool Executor Pattern in Java: Efficient Concurrent Task Management"
shortTitle: Thread-Pool Executor
description: "Learn the Thread-Pool Executor pattern in Java with practical examples, class
diagrams, and implementation details. Understand how to manage concurrent tasks efficiently,
improving resource utilization and application performance."
category: Concurrency
language: en
tag:

- Performance
- Resource Management
- Concurrency
- Multithreading
- Scalability

---

## Intent of Thread-Pool Executor Design Pattern

The Thread-Pool Executor pattern maintains a pool of worker threads to execute tasks concurrently,
optimizing resource usage by reusing existing threads instead of creating new ones for each task.

## Detailed Explanation of Thread-Pool Executor Pattern with Real-World Examples

### Real-world example

> Imagine a busy airport security checkpoint where instead of opening a new lane for each traveler,
> a fixed number of security lanes (threads) are open to process all passengers. Each security
> officer (thread) processes one passenger (task) at a time, and when finished, immediately calls the
> next passenger in line. During peak travel times, passengers wait in a queue, but the system is much
> more efficient than trying to open a new security lane for each individual traveler. The airport can
> handle fluctuating passenger traffic throughout the day with consistent staffing, optimizing both
> resource utilization and passenger throughput.

### In plain words

> Thread-Pool Executor keeps a set of reusable threads that process multiple tasks throughout their
> lifecycle, rather than creating a new thread for each task.

### Wikipedia says

> A thread pool is a software design pattern for achieving concurrency of execution in a computer
> program. Often also called a replicated workers or worker-crew model, a thread pool maintains
> multiple threads waiting for tasks to be allocated for concurrent execution by the supervising
> program.

### Class diagram

![Thread-pool-executor Class diagram](./etc/thread-pool-executor.urm.png)

## Programmatic Example of Thread-Pool Executor Pattern in Java

Imagine a hotel front desk.

The number of employees (thread pool) is limited, but guests (tasks) keep arriving endlessly.

The Thread-Pool Executor pattern efficiently handles a large number of requests by reusing a small
set of threads.

```java
@Slf4j
public class HotelFrontDesk {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// Hire 3 front desk employees (threads)
ExecutorService frontDesk = Executors.newFixedThreadPool(3);

LOGGER.info("Hotel front desk operation started!");

// 7 regular guests checking in (Runnable)
for (int i = 1; i <= 7; i++) {
String guestName = "Guest-" + i;
frontDesk.submit(() -> {
String employeeName = Thread.currentThread().getName();
LOGGER.info("{} is checking in {}...", employeeName, guestName);
try {
Thread.sleep(2000); // Simulate check-in time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
LOGGER.info("{} has been successfully checked in!", guestName);
});
}

// 3 VIP guests checking in (Callable with result)
Callable<String> vipGuest1 = createVipGuest("VIP-Guest-1");
Callable<String> vipGuest2 = createVipGuest("VIP-Guest-2");
Callable<String> vipGuest3 = createVipGuest("VIP-Guest-3");

Future<String> vipResult1 = frontDesk.submit(vipGuest1);
Future<String> vipResult2 = frontDesk.submit(vipGuest2);
Future<String> vipResult3 = frontDesk.submit(vipGuest3);

// Shutdown after submitting all tasks
frontDesk.shutdown();

if (frontDesk.awaitTermination(1, TimeUnit.HOURS)) {
// Print VIP guests' check-in results
LOGGER.info("VIP Check-in Results:");
LOGGER.info(vipResult1.get());
LOGGER.info(vipResult2.get());
LOGGER.info(vipResult3.get());
LOGGER.info("All guests have been successfully checked in. Front desk is now closed.");
} else {
LOGGER.info("Check-in timeout. Forcefully shutting down the front desk.");
}
}

private static Callable<String> createVipGuest(String vipGuestName) {
return () -> {
String employeeName = Thread.currentThread().getName();
LOGGER.info("{} is checking in VIP guest {}...", employeeName, vipGuestName);
Thread.sleep(1000); // VIPs are faster to check in
return vipGuestName + " has been successfully checked in!";
};
}
}
```

Here's the console output:

```markdown
Hotel front desk operation started!
pool-1-thread-3 is checking in Guest-3...
pool-1-thread-2 is checking in Guest-2...
pool-1-thread-1 is checking in Guest-1...
Guest-2 has been successfully checked in!
Guest-1 has been successfully checked in!
Guest-3 has been successfully checked in!
pool-1-thread-2 is checking in Guest-5...
pool-1-thread-3 is checking in Guest-4...
pool-1-thread-1 is checking in Guest-6...
Guest-5 has been successfully checked in!
pool-1-thread-2 is checking in Guest-7...
Guest-4 has been successfully checked in!
pool-1-thread-3 is checking in VIP guest VIP-Guest-1...
Guest-6 has been successfully checked in!
pool-1-thread-1 is checking in VIP guest VIP-Guest-2...
pool-1-thread-3 is checking in VIP guest VIP-Guest-3...
Guest-7 has been successfully checked in!
VIP Check-in Results:
VIP-Guest-1 has been successfully checked in!
VIP-Guest-2 has been successfully checked in!
VIP-Guest-3 has been successfully checked in!
All guests have been successfully checked in. Front desk is now closed.
```

**Note:** Since this example demonstrates asynchronous thread execution, **the actual output may vary between runs**. The order of execution and timing can differ due to thread scheduling, system load, and other factors that affect concurrent processing. The core behavior of the thread pool (limiting concurrent tasks to the number of threads and reusing threads) will remain consistent, but the exact sequence of log messages may change with each execution.

## When to Use the Thread-Pool Executor Pattern in Java

* When you need to limit the number of threads running simultaneously to avoid resource exhaustion
* For applications that process a large number of short-lived independent tasks
* To improve performance by reducing thread creation/destruction overhead
* When implementing server applications that handle multiple client requests concurrently
* To execute recurring tasks at fixed rates or with fixed delays

## Thread-Pool Executor Pattern Java Tutorial

* [Thread-Pool Executor Pattern Tutorial (Baeldung)](https://www.baeldung.com/thread-pool-java-and-guava)

## Real-World Applications of Thread-Pool Executor Pattern in Java

* Application servers like Tomcat and Jetty use thread pools to handle HTTP requests
* Database connection pools in JDBC implementations
* Background job processing frameworks like Spring Batch
* Task scheduling systems like Quartz Scheduler
* Java EE's Managed Executor Service for enterprise applications

## Benefits and Trade-offs of Thread-Pool Executor Pattern

### Benefits

* Improves performance by reusing existing threads instead of creating new ones
* Provides better resource management by limiting the number of active threads
* Simplifies thread lifecycle management and cleanup
* Facilitates easy implementation of task prioritization and scheduling
* Enhances application stability by preventing resource exhaustion

### Trade-offs

* May lead to thread starvation if improperly configured (too few threads)
* Potential for resource underutilization if improperly sized (too many threads)
* Requires careful shutdown handling to prevent task loss or resource leaks

## Related Java Design Patterns

* [Master-Worker Pattern](https://java-design-patterns.com/patterns/master-worker/): Tasks between a
master and multiple workers.
* [Producer-Consumer Pattern](https://java-design-patterns.com/patterns/producer-consumer/):
Separates task production and task consumption, typically using a blocking queue.
* [Object Pool Pattern](https://java-design-patterns.com/patterns/object-pool/): Reuses a set of
objects (e.g., threads) instead of creating/destroying them repeatedly.

## References and Credits

* [Java Documentation for ThreadPoolExecutor](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ThreadPoolExecutor.html)
* [Java Concurrency in Practice](https://jcip.net/) by Brian Goetz
* [Effective Java](https://www.oreilly.com/library/view/effective-java-3rd/9780134686097/) by Joshua
Bloch
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
66 changes: 66 additions & 0 deletions thread-pool-executor/etc/thread-pool-executor.urm.puml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
@startuml

interface Runnable {
+run(): void
}

interface Callable<T> {
+call(): T
}

interface ExecutorService {
+submit(task: Runnable): Future<?>
+submit(task: Callable<T>): Future<T>
+shutdown(): void
+awaitTermination(timeout: long, unit: TimeUnit): boolean
}

class ThreadPoolExecutor {
-corePoolSize: int
-maximumPoolSize: int
-keepAliveTime: long
-workQueue: BlockingQueue<Runnable>
+execute(task: Runnable): void
+submit(task: Callable<T>): Future<T>
}

class ThreadPoolManager {
-executorService: ExecutorService
+ThreadPoolManager(numThreads: int)
+submitTask(task: Runnable): void
+submitCallable(task: Callable<T>): Future<T>
+shutdown(): void
+awaitTermination(timeout: long, unit: TimeUnit): boolean
}

class Task {
-id: int
-name: String
-processingTime: long
+Task(id: int, name: String, processingTime: long)
+run(): void
+call(): TaskResult
}

class TaskResult {
-taskId: int
-taskName: String
-executionTime: long
+TaskResult(taskId: int, taskName: String, executionTime: long)
}

class App {
+main(args: String[]): void
-executeRunnableTasks(poolManager: ThreadPoolManager): void
-executeCallableTasks(poolManager: ThreadPoolManager): void
}

ExecutorService <|-- ThreadPoolExecutor : implements
Task ..|> Runnable : implements
Task ..|> Callable : implements
Task --> TaskResult : produces
ThreadPoolManager --> ExecutorService : wraps
App --> ThreadPoolManager : uses
App --> Task : creates

@enduml
83 changes: 83 additions & 0 deletions thread-pool-executor/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).

The MIT License
Copyright © 2014-2022 Ilkka Seppälä

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.26.0-SNAPSHOT</version>
</parent>

<artifactId>thread-pool-executor</artifactId>

<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<configuration>
<archive>
<manifest>
<mainClass>com.iluwatar.threadpoolexecutor.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Loading
Loading