50 lines
1.6 KiB
Markdown
50 lines
1.6 KiB
Markdown
# Problem 7.3: Compare different Executor implementations
|
|
|
|
## a)
|
|
|
|
Two important parameters of class `ThreadPoolExecutor` are `corePoolSize` and
|
|
`maximumPoolSize`. Read about their effect, e.g. at
|
|
<https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/util/concurrent/ThreadPoolExecutor.html>
|
|
or in *Java Concurreny in Practice*, chapter 8. Write an algorithm in pseudo
|
|
code that describes what happens when a new task is submitted and another algorithm
|
|
describing what happens when a task is finished. These two algorithms must use the
|
|
`corePoolSize` the `maximumPoolSize` and the `keepAliveTime`.
|
|
|
|
### Answer:
|
|
|
|
```js
|
|
function execute(runnable) {
|
|
if (runningThreads.size() < corePoolSize) {
|
|
createNewThread();
|
|
} else if (runningThreads.size() < maximumPoolSize && queue.isFull()) {
|
|
createNewThread();
|
|
}
|
|
}
|
|
|
|
function onTaskCompletion() {
|
|
if (runningThreads > corePoolSize) {
|
|
for (thread : runningThreads) {
|
|
if (thread.idleTime() > keepAliveTime) {
|
|
thread.terminate();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
```
|
|
|
|
## b)
|
|
|
|
Now consider the thread pools created by the factory methods
|
|
`newFixedThreadPool(int nThreads)` and `newCachedThreadPool()`
|
|
mentioned on slide 5-19 (you can find further details at
|
|
<https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/util/concurrent/Executors.html>):
|
|
How can you create these two kinds of thread pool using the general constructor `ThreadPoolExecutor()`?
|
|
|
|
|
|
### Answer:
|
|
|
|
```java
|
|
ThreadPoolExecutor fixedThreadPool = new ThreadPoolExecutor(n, n);
|
|
ThreadPoolExecutor cachedThreadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS);
|
|
``` |