-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathCustomThreadPoolExecutor.java
53 lines (45 loc) · 1.73 KB
/
CustomThreadPoolExecutor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package by.andd3dfx.multithreading.executor;
import by.andd3dfx.multithreading.queue.CustomBlockingQueue;
import by.andd3dfx.multithreading.queue.SynchronizedBlocksBasedBlockingQueue;
import lombok.SneakyThrows;
/**
* <pre>
* Write custom implementation of ThreadPoolExecutor that support next 2 methods: submit(Runnable) and shutdown().
*
* ThreadPoolExecutor creates numbers of TaskExecutor instances.
* TaskExecutor will be responsible for executing tasks.
* TaskExecutor exposes method submit() which will be called by task generating program, to submit a task.
*
* Based on <a href="http://www.makeinjava.com/custom-thread-pool-example-without-using-executor-framework/">article</a>
* </pre>
*
* @see <a href="https://youtu.be/FmJasJ-W-Rs">Video solution</a>
*/
public class CustomThreadPoolExecutor {
private static final int QUEUE_SIZE = 100;
private CustomBlockingQueue<Runnable> queue;
private volatile boolean isStopped = false;
public CustomThreadPoolExecutor(int threadsCount) {
queue = new SynchronizedBlocksBasedBlockingQueue<>(QUEUE_SIZE);
for (int i = 0; i < threadsCount; i++) {
TaskExecutor taskExecutor = new TaskExecutor(queue);
Thread thread = new Thread(taskExecutor, "Thread-" + i);
thread.start();
}
}
@SneakyThrows
public boolean submit(Runnable task) {
if (isStopped) {
System.out.println("Task rejected because of shutdown state");
return false;
}
queue.enqueue(task);
return true;
}
/**
* In shutdown state Thread Pool stops accepting new tasks
*/
public void shutdown() {
isStopped = true;
}
}