-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.java
More file actions
375 lines (307 loc) · 11.8 KB
/
ThreadPool.java
File metadata and controls
375 lines (307 loc) · 11.8 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package javaxt.utils;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
//******************************************************************************
//** ThreadPool
//******************************************************************************
/**
* Used to spawn threads and execute tasks. Instances of this class should
* override the process() method which is called by individual threads.
* Objects (e.g. data) are added to a queue via the add() method. Individual
* threads wait for data to be added to the queue. As new data is added,
* it is assigned to a thread to process. The thread, in turn, calls the
* process() method. The ThreadPool will run indefinitely, unless the done()
* method is called. The join() method can be used to join the ThreadPool
* to the caller's thread. Example:
*
<pre>
//Instantiate thread pool
int numThreads = 2;
ThreadPool pool = new ThreadPool(numThreads){
public void process(Object obj){
//Do something!
}
};
//Start the thread
pool.start();
//Add tiles to the pool
for (int i : new int[]{1,2,3,4,5,6,7,8,9,10}){
pool.add(i);
}
//Notify the pool that we have finished added records
pool.done();
//Wait for threads to finish
pool.join();
</pre>
*
******************************************************************************/
public class ThreadPool {
private int numThreads;
private Integer maxPoolSize;
private final ArrayList<Thread> threads;
private final ArrayList<Thread> activeThreads;
private final List pool;
private class Return{}
private ConcurrentHashMap<Long, HashMap<String, Object>> params;
//**************************************************************************
//** Constructor
//**************************************************************************
public ThreadPool(int numThreads, Integer maxPoolSize){
this.numThreads = numThreads;
threads = new ArrayList<>();
activeThreads = new ArrayList<>();
pool = new LinkedList();
if (maxPoolSize!=null){
if (maxPoolSize<1) maxPoolSize = null;
}
this.maxPoolSize = maxPoolSize;
params = new ConcurrentHashMap<>();
}
//**************************************************************************
//** Constructor
//**************************************************************************
public ThreadPool(int numThreads){
this(numThreads, null);
}
//**************************************************************************
//** start
//**************************************************************************
/** Used to initialize threads in the pool
*/
public ThreadPool start(){
threads.clear();
for (int i=0; i<numThreads; i++){
Thread t = new Thread(){
public void run(){
while (true) {
Object obj;
synchronized (pool) {
while (pool.isEmpty()) {
try {
pool.wait();
}
catch (InterruptedException e) {
return;
}
}
obj = pool.remove(0);
pool.notifyAll();
}
if ((obj instanceof Return)){
//Remove thread from the activeThreads array
synchronized(activeThreads){
for (int i=0; i<activeThreads.size(); i++){
if (activeThreads.get(i).getId()==this.getId()){
activeThreads.remove(i);
break;
}
}
//Add the object back to the pool for other threads to process
if (!activeThreads.isEmpty()) add(obj);
activeThreads.notify();
}
//Call the exit() callback and return
exit();
return;
}
else{
try{
//Call the process() callback
process(obj);
}
catch(Exception e){
//Remove thread from the activeThreads array
synchronized(activeThreads){
for (int i=0; i<activeThreads.size(); i++){
if (activeThreads.get(i).getId()==this.getId()){
activeThreads.remove(i);
break;
}
}
activeThreads.notify();
}
//Throw exception
throw e;
}
}
}
}
};
synchronized(activeThreads){
activeThreads.add(t);
activeThreads.notify();
}
t.start();
threads.add(t);
}
return this;
}
//**************************************************************************
//** process
//**************************************************************************
/** Called whenever a thread gets an object to process
*/
public void process(Object obj){}
//**************************************************************************
//** exit
//**************************************************************************
/** Called when a thread is being disposed
*/
public void exit(){}
//**************************************************************************
//** get
//**************************************************************************
/** Returns a variable for an individual thread
*/
public Object get(String key){
return get(key, null);
}
//**************************************************************************
//** get
//**************************************************************************
/** Returns a variable associated with an individual thread
* @param key The name of the variable
* @param setter Optional. Used to generate a value if the value has not
* been set. The following example shows how to call the get method with
* a setter as a lamba expression to return a new database connection:
<pre>
Connection conn = (Connection) get("conn", () -> {
return database.getConnection();
});
</pre>
*/
public Object get(String key, Setter setter) {
long id = getThreadID();
Object val = null;
synchronized(params){
HashMap<String, Object> map = params.get(id);
if (map==null && setter!=null){
map = new HashMap<>();
params.put(id, map);
}
if (map!=null){
val = map.get(key);
if (val==null && setter!=null){
try{
val = setter.getValue();
if (val==null) throw new Exception("Setter cannot return a null value");
map.put(key, val);
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
params.notifyAll();
}
return val;
}
//**************************************************************************
//** set
//**************************************************************************
/** Used to set a variable for an individual thread
*/
public void set(String key, Object value){
long id = getThreadID();
synchronized(params){
HashMap<String, Object> map = params.get(id);
if (map==null){
map = new HashMap<>();
params.put(id, map);
}
map.put(key, value);
params.notifyAll();
}
}
//**************************************************************************
//** getThreadID
//**************************************************************************
private long getThreadID(){
long id = Thread.currentThread().getId();
for (Thread t : threads){
if (id==t.getId()){
return id;
}
}
ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
for (Thread t : threads){
if (t.getThreadGroup().parentOf(threadGroup)){
return t.getId();
}
}
//ThreadGroup parentGroup = threadGroup.getParent();
throw new RuntimeException("Thread not found");
}
//**************************************************************************
//** Setter Interface
//**************************************************************************
public static interface Setter {
public Object getValue() throws Exception;
}
//**************************************************************************
//** add
//**************************************************************************
/** Used to add an object to the pool to process
* @return Integer representing the position in the queue
*/
public int add(Object object){
int idx;
synchronized (pool) {
if (maxPoolSize!=null){
while (pool.size()>maxPoolSize){
try{
pool.wait();
}
catch(java.lang.InterruptedException e){
break;
}
}
}
idx = pool.size();
pool.add(object);
pool.notify();
}
return idx;
}
//**************************************************************************
//** getActiveThreadCount
//**************************************************************************
/** Returns the number of active threads in the pool
*/
public int getActiveThreadCount(){
int count;
synchronized(activeThreads){
count = activeThreads.size();
}
return count;
}
//**************************************************************************
//** getQueue
//**************************************************************************
/** Returns a handle to the job queue. Use with care. Be sure to add a
* synchronized block when processing or iterating through items in the
* queue.
*/
public List getQueue(){
return pool;
}
//**************************************************************************
//** done
//**************************************************************************
/** Used to notify the threads that we are done adding objects to the pool
* and to exit when ready
*/
public void done(){
add(new Return());
}
//**************************************************************************
//** join
//**************************************************************************
/** Used to wait for threads to complete
*/
public void join() throws InterruptedException {
for (Thread thread : threads){
thread.join();
}
}
}