refactor: remove tls and thread pool

This commit is contained in:
Ilkka Seppälä
2024-05-24 20:56:06 +03:00
parent 518ffa4d4d
commit 3a38e2be6b
23 changed files with 0 additions and 1480 deletions
-2
View File
@@ -108,7 +108,6 @@
<module>double-dispatch</module>
<module>multiton</module>
<module>resource-acquisition-is-initialization</module>
<module>thread-pool</module>
<module>twin</module>
<module>private-class-data</module>
<module>object-pool</module>
@@ -205,7 +204,6 @@
<module>identity-map</module>
<module>component</module>
<module>context-object</module>
<module>thread-local-storage</module>
<module>optimistic-offline-lock</module>
<module>curiously-recurring-template-pattern</module>
<module>log-aggregation</module>
-219
View File
@@ -1,219 +0,0 @@
---
title: Thread Local Storage
category: Concurrency
language: en
tag:
- Isolation
- Memory management
- Thread management
---
## Also known as
* TLS
* Thread-Specific Storage
## Intent
To provide each thread with its own isolated instance of a variable, avoiding shared access and synchronization issues.
## Explanation
Real-world example
> Imagine a busy restaurant where each waiter has their own personal notepad to take orders from customers. Each waiter's notepad is separate and used only by that specific waiter. This setup ensures that no waiter interferes with another's orders, avoiding confusion and mistakes. In this analogy, the restaurant represents the application, the waiters represent the threads, and the notepads represent thread-local storage, where each thread maintains its own isolated data.
In plain words
> Thread Local Storage provides each thread with its own isolated instance of a variable, eliminating the need for synchronization and avoiding shared access issues.
Wikipedia says
> In computer programming, thread-local storage (TLS) is a memory management method that uses static or global memory local to a thread. The concept allows storage of data that appears to be global in a system with separate threads.
**Programmatic Example**
Consider a scenario where threads need to maintain their own state without interfering with each other. We'll demonstrate this with two implementations:
1. With ThreadLocal: Each thread has its own isolated instance of a variable.
2. Without ThreadLocal: Threads share a single instance of a variable, leading to potential conflicts.
We start walking through the code from the base class.
**AbstractThreadLocalExample**
* Implements `Runnable` and includes `run` method which pauses the thread, prints the current value, and then changes it.
* `getter` and `setter` methods are abstract and will be implemented by subclasses.
```java
public abstract class AbstractThreadLocalExample implements Runnable {
private static final Random RND = new Random();
@Override
public void run() {
try {
// Pause thread for a random duration
Thread.sleep(RND.nextInt(1000));
// Print the current value before changing it
System.out.println(getCurrentThreadName() + ", before value changing: " + getter().get());
// Change the value
setter().accept(RND.nextInt(1000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
protected abstract Consumer<Integer> setter();
protected abstract Supplier<Integer> getter();
private String getCurrentThreadName() {
return Thread.currentThread().getName();
}
}
```
**WithThreadLocal**
* Uses `ThreadLocal` to ensure each thread has its own instance of `value`.
```java
public class WithThreadLocal extends AbstractThreadLocalExample {
private ThreadLocal<Integer> value = ThreadLocal.withInitial(() -> 0);
@Override
protected Consumer<Integer> setter() {
return value::set;
}
@Override
protected Supplier<Integer> getter() {
return value::get;
}
}
```
**WithoutThreadLocal**
* Uses a shared `value` among all threads, demonstrating potential interference between threads.
```java
public class WithoutThreadLocal extends AbstractThreadLocalExample {
private Integer value = 0;
@Override
protected Consumer<Integer> setter() {
return integer -> value = integer;
}
@Override
protected Supplier<Integer> getter() {
return () -> value;
}
}
```
**ThreadLocalTest**
* Tests both implementations by creating two threads for each and verifying their behavior.
```java
public class ThreadLocalTest {
@Test
public void withoutThreadLocal() throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 0; i < 2; i++) {
executor.submit(new WithoutThreadLocal());
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
public void withThreadLocal() throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 0; i < 2; i++) {
executor.submit(new WithThreadLocal());
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
}
}
```
The output of test named withThreadLocal:
```
pool-2-thread-2, before value changing: 1234567890
pool-2-thread-1, before value changing: 1234567890
```
And the output of withoutThreadLocal:
```
pool-1-thread-2, before value changing: 1234567890
pool-1-thread-1, before value changing: 848843054
```
Where 1234567890 is our initial value. We see that in test withoutThreadLocal thread 2 got out from LockSupport#parkNanos earlier than the first and change value in shared variable.
This example demonstrates how `ThreadLocal` variables provide isolated storage for each thread, preventing interference from other threads, whereas shared variables can lead to unexpected changes and thread interference.
## Class diagram
![Thread Local Storage](./etc/thread-local-storage.urm.png "Thread Local Storage")
## Applicability
* Use when you need to avoid synchronization for performance reasons by providing each thread with its own instance of a variable.
* Useful in scenarios where threads need to maintain state information independently of other threads.
* Suitable for managing per-thread lifecycle states in web servers or handling thread-local configuration in multithreaded applications.
## Tutorials
* [An Introduction to ThreadLocal in Java - Baeldung](https://www.baeldung.com/java-threadlocal)
## Known uses
* Java ThreadLocal class, commonly used to manage user sessions in web applications.
* Database connections, where each thread gets its own connection instance.
* Locale settings in internationalized applications to ensure thread-specific locale information.
* In java.lang.Thread during thread initialization
* In java.net.URL to prevent recursive provider lookups
* In org.junit.runners.BlockJUnit4ClassRunner to contain current rule
* In org.springframework:spring-web to store request context
* In org.apache.util.net.Nio2Endpoint to allow detecting if a completion handler completes inline
* In io.micrometer to avoid problems with not thread-safe NumberFormat
## Consequences
Benefits:
* Eliminates the need for synchronization, which can improve performance in multithreaded environments.
* Simplifies design by avoiding complex synchronization mechanisms.
* Each thread has its own dedicated storage, reducing contention.
Trade-offs:
* Increased memory usage due to multiple instances of the variable.
* Potential for memory leaks if thread-local variables are not properly managed, especially in long-running applications or thread pools.
* Debugging can be more complex due to thread-specific storage behavior.
## Related Patterns
* [Singleton](https://java-design-patterns.com/patterns/singleton/): Both patterns ensure a unique instance of a variable, but Thread Local Storage ensures one per thread rather than one per application.
* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): While Flyweight shares instances to minimize memory usage, Thread Local Storage creates separate instances for each thread.
## Credits
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
* [Effective Java](https://amzn.to/4cGk2Jz)
* [Java Concurrency in Practice](https://amzn.to/4aRMruW)
* [A Deep dive into (implicit) Thread Local Storage - Chao-tic](https://chao-tic.github.io/blog/2018/12/25/tls)
* [ELF Handling for Thread-Local Storage - Red Hat Inc.](https://uclibc.org/docs/tls.pdf)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

@@ -1,29 +0,0 @@
@startuml
package com.iluwatar {
abstract class AbstractThreadLocalExample {
- RANDOM_THREAD_PARK_END : Integer {static}
- RANDOM_THREAD_PARK_START : Integer {static}
- RND : SecureRandom {static}
+ AbstractThreadLocalExample()
- getThreadName() : String
# getter() : Supplier<Integer> {abstract}
+ run()
# setter() : Consumer<Integer> {abstract}
}
class WithThreadLocal {
- value : ThreadLocal<Integer>
+ WithThreadLocal(value : ThreadLocal<Integer>)
# getter() : Supplier<Integer>
+ remove()
# setter() : Consumer<Integer>
}
class WithoutThreadLocal {
- value : Integer
+ WithoutThreadLocal(value : Integer)
# getter() : Supplier<Integer>
# setter() : Consumer<Integer>
}
}
WithThreadLocal --|> AbstractThreadLocalExample
WithoutThreadLocal --|> AbstractThreadLocalExample
@enduml
-46
View File
@@ -1,46 +0,0 @@
<?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-local-storage</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -1,70 +0,0 @@
/*
* 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.
*/
package com.iluwatar;
import java.security.SecureRandom;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Consumer;
import java.util.function.Supplier;
import lombok.extern.slf4j.Slf4j;
/**
* Class with main logic.
*/
@Slf4j
public abstract class AbstractThreadLocalExample implements Runnable {
private static final SecureRandom RND = new SecureRandom();
private static final Integer RANDOM_THREAD_PARK_START = 1_000_000_000;
private static final Integer RANDOM_THREAD_PARK_END = 2_000_000_000;
@Override
public void run() {
long nanosToPark = RND.nextInt(RANDOM_THREAD_PARK_START, RANDOM_THREAD_PARK_END);
LockSupport.parkNanos(nanosToPark);
System.out.println(getThreadName() + ", before value changing: " + getter().get());
setter().accept(RND.nextInt());
}
/**
* Setter for our value.
*
* @return consumer
*/
protected abstract Consumer<Integer> setter();
/**
* Getter for our value.
*
* @return supplier
*/
protected abstract Supplier<Integer> getter();
private String getThreadName() {
return Thread.currentThread().getName();
}
}
@@ -1,55 +0,0 @@
/*
* 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.
*/
package com.iluwatar;
import java.util.function.Consumer;
import java.util.function.Supplier;
import lombok.AllArgsConstructor;
/**
* Example of runnable with use of {@link ThreadLocal}.
*/
@AllArgsConstructor
public class WithThreadLocal extends AbstractThreadLocalExample {
private final ThreadLocal<Integer> value;
/**
* Removes the current thread's value for this thread-local variable.
*/
public void remove() {
this.value.remove();
}
@Override
protected Consumer<Integer> setter() {
return value::set;
}
@Override
protected Supplier<Integer> getter() {
return value::get;
}
}
@@ -1,48 +0,0 @@
/*
* 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.
*/
package com.iluwatar;
import java.util.function.Consumer;
import java.util.function.Supplier;
import lombok.AllArgsConstructor;
/**
* Example of runnable without usage of {@link ThreadLocal}.
*/
@AllArgsConstructor
public class WithoutThreadLocal extends AbstractThreadLocalExample {
private Integer value;
@Override
protected Consumer<Integer> setter() {
return integer -> value = integer;
}
@Override
protected Supplier<Integer> getter() {
return () -> value;
}
}
@@ -1,91 +0,0 @@
/*
* 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.
*/
import com.iluwatar.WithThreadLocal;
import com.iluwatar.WithoutThreadLocal;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadLocalTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
@BeforeEach
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@AfterEach
public void restoreStreams() {
System.setOut(originalOut);
}
@Test
public void withoutThreadLocal() throws InterruptedException {
int initialValue = 1234567890;
int threadSize = 2;
ExecutorService executor = Executors.newFixedThreadPool(threadSize);
for (int i = 0; i < threadSize; i++) {
//Create independent thread
WithoutThreadLocal threadLocal = new WithoutThreadLocal(initialValue);
executor.submit(threadLocal);
}
executor.awaitTermination(3, TimeUnit.SECONDS);
List<String> lines = outContent.toString().lines().toList();
Assertions.assertTrue(lines.stream()
.allMatch(line -> line.endsWith(String.valueOf(initialValue))));
}
@Test
public void withThreadLocal() throws InterruptedException {
int initialValue = 1234567890;
int threadSize = 2;
ExecutorService executor = Executors.newFixedThreadPool(threadSize);
WithThreadLocal threadLocal = new WithThreadLocal(ThreadLocal.withInitial(() -> initialValue));
for (int i = 0; i < threadSize; i++) {
executor.submit(threadLocal);
}
executor.awaitTermination(3, TimeUnit.SECONDS);
threadLocal.remove();
List<String> lines = outContent.toString().lines().toList();
Assertions.assertTrue(lines.stream()
.allMatch(line -> line.endsWith(String.valueOf(initialValue))));
}
}
-219
View File
@@ -1,219 +0,0 @@
---
title: Thread Pool
category: Concurrency
language: en
tag:
- Asynchronous
- Performance
- Resource management
- Scalability
- Synchronization
- Thread management
---
## Also known as
* Worker Pool
## Intent
Efficiently manage a pool of worker threads to execute tasks concurrently, improving resource utilization and performance.
## Explanation
Real-world example
> A real-world analogy for the Thread Pool design pattern can be found in a restaurant kitchen. Imagine a busy restaurant with a limited number of chefs (threads). Instead of hiring a new chef every time an order (task) comes in, the restaurant uses a fixed number of chefs to handle all the incoming orders. Each chef works on one order at a time and then moves on to the next one when finished. This approach ensures that the kitchen operates efficiently without the overhead of hiring and firing chefs continuously, and it prevents the kitchen from becoming overcrowded with too many chefs working at once. This setup allows the restaurant to handle multiple orders concurrently, optimize resource use, and maintain a steady workflow.
In plain words
> Thread Pool is a concurrency pattern where threads are allocated once and reused between tasks.
Wikipedia says
> In computer programming, 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. By maintaining a pool of threads, the model increases performance and avoids latency in execution due to frequent creation and destruction of threads for short-lived tasks. The number of available threads is tuned to the computing resources available to the program, such as a parallel task queue after completion of execution.
**Programmatic Example**
Let's first look at our task hierarchy. We have an abstract base class `Task` and concrete tasks `CoffeeMakingTask` and `PotatoPeelingTask`.
```java
public abstract class Task {
private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
@Getter
private final int id;
@Getter
private final int timeMs;
public Task(final int timeMs) {
this.id = ID_GENERATOR.incrementAndGet();
this.timeMs = timeMs;
}
@Override
public String toString() {
return String.format("id=%d timeMs=%d", id, timeMs);
}
}
public class CoffeeMakingTask extends Task {
private static final int TIME_PER_CUP = 100;
public CoffeeMakingTask(int numCups) {
super(numCups * TIME_PER_CUP);
}
@Override
public String toString() {
return String.format("%s %s", this.getClass().getSimpleName(), super.toString());
}
}
public class PotatoPeelingTask extends Task {
private static final int TIME_PER_POTATO = 200;
public PotatoPeelingTask(int numPotatoes) {
super(numPotatoes * TIME_PER_POTATO);
}
@Override
public String toString() {
return String.format("%s %s", this.getClass().getSimpleName(), super.toString());
}
}
```
Next, we present a runnable `Worker` class that the thread pool will utilize to handle all the potato peeling and coffee making.
```java
@Slf4j
public class Worker implements Runnable {
private final Task task;
public Worker(final Task task) {
this.task = task;
}
@Override
public void run() {
LOGGER.info("{} processing {}", Thread.currentThread().getName(), task.toString());
try {
Thread.sleep(task.getTimeMs());
} catch (InterruptedException e) {
LOGGER.error("Error occurred: ", e);
}
}
}
```
Now, we are ready to show the full example in action.
```java
LOGGER.info("Program started");
// Create a list of tasks to be executed
var tasks = List.of(
new PotatoPeelingTask(3),
new PotatoPeelingTask(6),
new CoffeeMakingTask(2),
new CoffeeMakingTask(6),
new PotatoPeelingTask(4),
new CoffeeMakingTask(2),
new PotatoPeelingTask(4),
new CoffeeMakingTask(9),
new PotatoPeelingTask(3),
new CoffeeMakingTask(2),
new PotatoPeelingTask(4),
new CoffeeMakingTask(2),
new CoffeeMakingTask(7),
new PotatoPeelingTask(4),
new PotatoPeelingTask(5));
// Creates a thread pool that reuses a fixed number of threads operating off a shared
// unbounded queue. At any point, at most nThreads threads will be active processing
// tasks. If additional tasks are submitted when all threads are active, they will wait
// in the queue until a thread is available.
var executor = Executors.newFixedThreadPool(3);
// Allocate new worker for each task
// The worker is executed when a thread becomes
// available in the thread pool
tasks.stream().map(Worker::new).forEach(executor::execute);
// All tasks were executed, now shutdown
executor.shutdown();
while (!executor.isTerminated()) {
Thread.yield();
}
LOGGER.info("Program finished");
```
Running the example produces the following output:
```
13:47:07.244 [main] INFO com.iluwatar.threadpool.App -- Program started
13:47:07.258 [pool-1-thread-3] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-3 processing CoffeeMakingTask id=3 timeMs=200
13:47:07.258 [pool-1-thread-2] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-2 processing PotatoPeelingTask id=2 timeMs=1200
13:47:07.258 [pool-1-thread-1] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-1 processing PotatoPeelingTask id=1 timeMs=600
13:47:07.464 [pool-1-thread-3] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-3 processing CoffeeMakingTask id=4 timeMs=600
13:47:07.864 [pool-1-thread-1] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-1 processing PotatoPeelingTask id=5 timeMs=800
13:47:08.066 [pool-1-thread-3] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-3 processing CoffeeMakingTask id=6 timeMs=200
13:47:08.271 [pool-1-thread-3] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-3 processing PotatoPeelingTask id=7 timeMs=800
13:47:08.464 [pool-1-thread-2] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-2 processing CoffeeMakingTask id=8 timeMs=900
13:47:08.668 [pool-1-thread-1] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-1 processing PotatoPeelingTask id=9 timeMs=600
13:47:09.076 [pool-1-thread-3] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-3 processing CoffeeMakingTask id=10 timeMs=200
13:47:09.273 [pool-1-thread-1] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-1 processing PotatoPeelingTask id=11 timeMs=800
13:47:09.277 [pool-1-thread-3] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-3 processing CoffeeMakingTask id=12 timeMs=200
13:47:09.367 [pool-1-thread-2] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-2 processing CoffeeMakingTask id=13 timeMs=700
13:47:09.482 [pool-1-thread-3] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-3 processing PotatoPeelingTask id=14 timeMs=800
13:47:10.072 [pool-1-thread-2] INFO com.iluwatar.threadpool.Worker -- pool-1-thread-2 processing PotatoPeelingTask id=15 timeMs=1000
13:47:11.078 [main] INFO com.iluwatar.threadpool.App -- Program finished
```
## Class diagram
![Thread Pool](./etc/thread_pool_urm.png "Thread Pool")
## Applicability
* When there are multiple tasks to be executed and creating a new thread for each task would be inefficient.
* In scenarios where tasks are short-lived and the overhead of thread creation and destruction is significant.
* When you need to control the number of concurrent threads to prevent resource exhaustion.
## Known Uses
* Java's `java.util.concurrent.ExecutorService` and `ThreadPoolExecutor`.
* Web servers handling multiple client requests concurrently.
* Background task execution in GUI applications to keep the user interface responsive.
## Consequences
Benefits:
* Improved performance by reusing existing threads instead of creating new ones.
* Better resource management by limiting the number of active threads.
* Simplifies the management of concurrent task execution.
Trade-offs:
* Requires careful tuning of the thread pool size to balance resource utilization and performance.
* Potential for thread starvation if the pool size is too small.
* Complexity in handling task rejection and thread lifecycle management.
## Related Patterns
* [Promise](https://java-design-patterns.com/patterns/promise/): Used to represent the result of an asynchronous computation, often executed by a thread pool.
* [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Threads in the pool consume tasks produced by another part of the application.
* [Command](https://java-design-patterns.com/patterns/command/): Each task submitted to the thread pool can be treated as a command object.
## Credits
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
* [Effective Java](https://amzn.to/4cGk2Jz)
* [Java Concurrency in Practice](https://amzn.to/4aRMruW)
-37
View File
@@ -1,37 +0,0 @@
@startuml
package com.iluwatar.threadpool {
class App {
- LOGGER : Logger {static}
+ App()
+ main(args : String[]) {static}
}
class CoffeeMakingTask {
- TIME_PER_CUP : int {static}
+ CoffeeMakingTask(numCups : int)
+ toString() : String
}
class PotatoPeelingTask {
- TIME_PER_POTATO : int {static}
+ PotatoPeelingTask(numPotatoes : int)
+ toString() : String
}
abstract class Task {
- ID_GENERATOR : AtomicInteger {static}
- id : int
- timeMs : int
+ Task(timeMs : int)
+ getId() : int
+ getTimeMs() : int
+ toString() : String
}
class Worker {
- LOGGER : Logger {static}
- task : Task
+ Worker(task : Task)
+ run()
}
}
Worker --> "-task" Task
CoffeeMakingTask --|> Task
PotatoPeelingTask --|> Task
@enduml
Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

-67
View File
@@ -1,67 +0,0 @@
<?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</artifactId>
<dependencies>
<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.threadpool.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -1,92 +0,0 @@
/*
* 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.
*/
package com.iluwatar.threadpool;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.extern.slf4j.Slf4j;
/**
* Thread Pool pattern is where a number of threads are created to perform a number of tasks, which
* are usually organized in a queue. The results from the tasks being executed might also be placed
* in a queue, or the tasks might return no result. Typically, there are many more tasks than
* threads. As soon as a thread completes its task, it will request the next task from the queue
* until all tasks have been completed. The thread can then terminate, or sleep until there are new
* tasks available.
*
* <p>In this example we create a list of tasks presenting work to be done. Each task is then
* wrapped into a {@link Worker} object that implements {@link Runnable}. We create an {@link
* ExecutorService} with fixed number of threads (Thread Pool) and use them to execute the {@link
* Worker}s.
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
LOGGER.info("Program started");
// Create a list of tasks to be executed
var tasks = List.of(
new PotatoPeelingTask(3),
new PotatoPeelingTask(6),
new CoffeeMakingTask(2),
new CoffeeMakingTask(6),
new PotatoPeelingTask(4),
new CoffeeMakingTask(2),
new PotatoPeelingTask(4),
new CoffeeMakingTask(9),
new PotatoPeelingTask(3),
new CoffeeMakingTask(2),
new PotatoPeelingTask(4),
new CoffeeMakingTask(2),
new CoffeeMakingTask(7),
new PotatoPeelingTask(4),
new PotatoPeelingTask(5));
// Creates a thread pool that reuses a fixed number of threads operating off a shared
// unbounded queue. At any point, at most nThreads threads will be active processing
// tasks. If additional tasks are submitted when all threads are active, they will wait
// in the queue until a thread is available.
var executor = Executors.newFixedThreadPool(3);
// Allocate new worker for each task
// The worker is executed when a thread becomes
// available in the thread pool
tasks.stream().map(Worker::new).forEach(executor::execute);
// All tasks were executed, now shutdown
executor.shutdown();
while (!executor.isTerminated()) {
Thread.yield();
}
LOGGER.info("Program finished");
}
}
@@ -1,42 +0,0 @@
/*
* 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.
*/
package com.iluwatar.threadpool;
/**
* CoffeeMakingTask is a concrete task.
*/
public class CoffeeMakingTask extends Task {
private static final int TIME_PER_CUP = 100;
public CoffeeMakingTask(int numCups) {
super(numCups * TIME_PER_CUP);
}
@Override
public String toString() {
return String.format("%s %s", this.getClass().getSimpleName(), super.toString());
}
}
@@ -1,42 +0,0 @@
/*
* 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.
*/
package com.iluwatar.threadpool;
/**
* PotatoPeelingTask is a concrete task.
*/
public class PotatoPeelingTask extends Task {
private static final int TIME_PER_POTATO = 200;
public PotatoPeelingTask(int numPotatoes) {
super(numPotatoes * TIME_PER_POTATO);
}
@Override
public String toString() {
return String.format("%s %s", this.getClass().getSimpleName(), super.toString());
}
}
@@ -1,51 +0,0 @@
/*
* 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.
*/
package com.iluwatar.threadpool;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.Getter;
/**
* Abstract base class for tasks.
*/
public abstract class Task {
private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
@Getter
private final int id;
@Getter
private final int timeMs;
public Task(final int timeMs) {
this.id = ID_GENERATOR.incrementAndGet();
this.timeMs = timeMs;
}
@Override
public String toString() {
return String.format("id=%d timeMs=%d", id, timeMs);
}
}
@@ -1,51 +0,0 @@
/*
* 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.
*/
package com.iluwatar.threadpool;
import lombok.extern.slf4j.Slf4j;
/**
* Worker implements {@link Runnable} and thus can be executed by {@link
* java.util.concurrent.ExecutorService}.
*/
@Slf4j
public class Worker implements Runnable {
private final Task task;
public Worker(final Task task) {
this.task = task;
}
@Override
public void run() {
LOGGER.info("{} processing {}", Thread.currentThread().getName(), task.toString());
try {
Thread.sleep(task.getTimeMs());
} catch (InterruptedException e) {
LOGGER.error("Error occurred: ", e);
}
}
}
@@ -1,41 +0,0 @@
/*
* 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.
*/
package com.iluwatar.threadpool;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*
*/
class AppTest {
@Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
@@ -1,40 +0,0 @@
/*
* 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.
*/
package com.iluwatar.threadpool;
/**
* CoffeeMakingTaskTest
*
*/
class CoffeeMakingTaskTest extends TaskTest<CoffeeMakingTask> {
/**
* Create a new test instance
*/
public CoffeeMakingTaskTest() {
super(CoffeeMakingTask::new, 100);
}
}
@@ -1,40 +0,0 @@
/*
* 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.
*/
package com.iluwatar.threadpool;
/**
* PotatoPeelingTaskTest
*
*/
class PotatoPeelingTaskTest extends TaskTest<PotatoPeelingTask> {
/**
* Create a new test instance
*/
public PotatoPeelingTaskTest() {
super(PotatoPeelingTask::new, 200);
}
}
@@ -1,145 +0,0 @@
/*
* 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.
*/
package com.iluwatar.threadpool;
import static java.time.Duration.ofMillis;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
/**
* Test for Tasks using a Thread Pool
*
* @param <T> Type of Task
*/
public abstract class TaskTest<T extends Task> {
/**
* The number of tasks used during the concurrency test
*/
private static final int TASK_COUNT = 128 * 1024;
/**
* The number of threads used during the concurrency test
*/
private static final int THREAD_COUNT = 8;
/**
* The task factory, used to create new test items
*/
private final IntFunction<T> factory;
/**
* The expected time needed to run the task 1 single time, in milli seconds
*/
private final int expectedExecutionTime;
/**
* Create a new test instance
*
* @param factory The task factory, used to create new test items
* @param expectedExecutionTime The expected time needed to run the task 1 time, in milli seconds
*/
public TaskTest(final IntFunction<T> factory, final int expectedExecutionTime) {
this.factory = factory;
this.expectedExecutionTime = expectedExecutionTime;
}
/**
* Verify if the generated id is unique for each task, even if the tasks are created in separate
* threads
*/
@Test
void testIdGeneration() {
assertTimeout(ofMillis(10000), () -> {
final var service = Executors.newFixedThreadPool(THREAD_COUNT);
final var tasks = IntStream.range(0, TASK_COUNT)
.<Callable<Integer>>mapToObj(i -> () -> factory.apply(1).getId())
.collect(Collectors.toCollection(ArrayList::new));
final var ids = service.invokeAll(tasks)
.stream()
.map(TaskTest::get)
.filter(Objects::nonNull)
.toList();
service.shutdownNow();
final var uniqueIdCount = ids.stream()
.distinct()
.count();
assertEquals(TASK_COUNT, ids.size());
assertEquals(TASK_COUNT, uniqueIdCount);
});
}
/**
* Verify if the time per execution of a task matches the actual time required to execute the task
* a given number of times
*/
@Test
void testTimeMs() {
for (var i = 0; i < 10; i++) {
assertEquals(this.expectedExecutionTime * i, this.factory.apply(i).getTimeMs());
}
}
/**
* Verify if the task has some sort of {@link T#toString()}, different from 'null'
*/
@Test
void testToString() {
assertNotNull(this.factory.apply(0).toString());
}
/**
* Extract the result from a future or returns 'null' when an exception occurred
*
* @param future The future we want the result from
* @param <O> The result type
* @return The result or 'null' when a checked exception occurred
*/
private static <O> O get(Future<O> future) {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
return null;
}
}
}
@@ -1,53 +0,0 @@
/*
* 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.
*/
package com.iluwatar.threadpool;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.junit.jupiter.api.Test;
/**
* WorkerTest
*
*/
class WorkerTest {
/**
* Verify if a worker does the actual job
*/
@Test
void testRun() {
final var task = mock(Task.class);
final var worker = new Worker(task);
verifyNoMoreInteractions(task);
worker.run();
verify(task).getTimeMs();
verifyNoMoreInteractions(task);
}
}