-
Notifications
You must be signed in to change notification settings - Fork 333
Expand file tree
/
Copy pathUsingExecutors.java
More file actions
198 lines (180 loc) · 6.35 KB
/
Copy pathUsingExecutors.java
File metadata and controls
198 lines (180 loc) · 6.35 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package br.com.leonardoz.features.executors;
import java.util.LinkedList;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* Thread creation is expensive and difficult to manage.
*
* Executors help us to decouple task submission from execution.
*
* We have 6 types of executors:
*
* - Single Thread Executor: Uses a single worker to process tasks.
*
* - Cached Thread Pool: Unbounded thread limit, good performance for long
* running tasks.
*
* - Fixed Thread Pool: Bounded thread limit, maintains the same thread pool
* size.
*
* - Scheduled Thread Pool: Bounded thread limit, used for delayed tasks.
*
* - Single-Thread Scheduled Pool: Similar to the scheduled thread pool, but
* single-threaded, with only one active task at the time.
*
* - Work-Stealing Thread Pool: Based on Fork/Join Framework, applies the
* work-stealing algorithm for balancing tasks, with available processors as a
* paralellism level.
*
* And 2 types of tasks:
*
* - execute: Executes without giving feedback. Fire-and-forget.
*
* - submit: Returns a FutureTask.
*
* ThreadPools: Used by the executors described above. ThreadPoolExecutor can be
* used to create custom Executors.
*
* shutdown() -> Waits for tasks to terminate and release resources.
* shutdownNow() -> Try to stops all executing tasks and returns a list of not
* executed tasks.
*
*/
public class UsingExecutors {
public static void usingSingleThreadExecutor() {
System.out.println("=== SingleThreadExecutor ===");
var singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(() -> System.out.println("Print this."));
singleThreadExecutor.execute(() -> System.out.println("and this one to."));
singleThreadExecutor.shutdown();
try {
singleThreadExecutor.awaitTermination(4, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\n\n");
}
public static void usingCachedThreadPool() {
System.out.println("=== CachedThreadPool ===");
var cachedThreadPool = Executors.newCachedThreadPool();
var uuids = new LinkedList<Future<UUID>>();
for (int i = 0; i < 10; i++) {
var submittedUUID = cachedThreadPool.submit(() -> {
var randomUUID = UUID.randomUUID();
System.out.println("UUID " + randomUUID + " from " + Thread.currentThread().getName());
return randomUUID;
});
uuids.add(submittedUUID);
}
cachedThreadPool.execute(() -> uuids.forEach((f) -> {
try {
System.out.println("Result " + f.get() + " from thread " + Thread.currentThread().getName());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}));
cachedThreadPool.shutdown();
try {
cachedThreadPool.awaitTermination(4, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\n\n");
}
public static void usingFixedThreadPool() {
System.out.println("=== FixedThreadPool ===");
var fixedPool = Executors.newFixedThreadPool(4);
var uuids = new LinkedList<Future<UUID>>();
for (int i = 0; i < 20; i++) {
var submitted = fixedPool.submit(() -> {
var randomUUID = UUID.randomUUID();
System.out.println("UUID " + randomUUID + " from " + Thread.currentThread().getName());
return randomUUID;
});
uuids.add(submitted);
}
fixedPool.execute(() -> uuids.forEach((f) -> {
try {
System.out.println("Result " + f.get() + " from " + Thread.currentThread().getName());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}));
fixedPool.shutdown();
try {
fixedPool.awaitTermination(4, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\n\n");
}
public static void usingScheduledThreadPool() {
System.out.println("=== ScheduledThreadPool ===");
var scheduledThreadPool = Executors.newScheduledThreadPool(4);
scheduledThreadPool.scheduleAtFixedRate(() -> System.out.println("1) Print every 2s"), 0, 2, TimeUnit.SECONDS);
scheduledThreadPool.scheduleAtFixedRate(() -> System.out.println("2) Print every 2s"), 0, 2, TimeUnit.SECONDS);
scheduledThreadPool.scheduleWithFixedDelay(() -> System.out.println("3) Print every 2s delay"), 0, 2,
TimeUnit.SECONDS);
try {
scheduledThreadPool.awaitTermination(6, TimeUnit.SECONDS);
scheduledThreadPool.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\n\n");
}
public static void usingSingleTreadScheduledExecutor() {
System.out.println("=== SingleThreadScheduledThreadPool ===");
var singleThreadScheduler = Executors.newSingleThreadScheduledExecutor();
singleThreadScheduler.scheduleAtFixedRate(() -> System.out.println("1) Print every 2s"), 0, 2, TimeUnit.SECONDS);
singleThreadScheduler.scheduleWithFixedDelay(() -> System.out.println("2) Print every 2s delay"), 0, 2,
TimeUnit.SECONDS);
try {
singleThreadScheduler.awaitTermination(6, TimeUnit.SECONDS);
singleThreadScheduler.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\n\n");
}
public static void usingWorkStealingThreadPool() {
System.out.println("=== WorkStealingThreadPool ===");
var workStealingPool = Executors.newWorkStealingPool();
workStealingPool.execute(() -> System.out.println("Prints normally"));
Callable<UUID> generatesUUID = UUID::randomUUID;
var severalUUIDsTasks = new LinkedList<Callable<UUID>>();
for (int i = 0; i < 20; i++) {
severalUUIDsTasks.add(generatesUUID);
}
try {
var futureUUIDs = workStealingPool.invokeAll(severalUUIDsTasks);
for (var future : futureUUIDs) {
if (future.isDone()) {
var uuid = future.get();
System.out.println("New UUID :" + uuid);
}
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
try {
workStealingPool.awaitTermination(6, TimeUnit.SECONDS);
workStealingPool.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\n\n");
}
public static void main(String[] args) {
usingSingleThreadExecutor();
usingCachedThreadPool();
usingFixedThreadPool();
usingScheduledThreadPool();
usingSingleTreadScheduledExecutor();
usingWorkStealingThreadPool();
}
}