-
Notifications
You must be signed in to change notification settings - Fork 33
/
ThreadPool.java
680 lines (605 loc) · 20.8 KB
/
ThreadPool.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
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
/*
* Copyright (c) 2000, 2017 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020 Payara Services Ltd.
* Copyright (c) 2021, 2022 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
/*
* @(#)ThreadPool.java 1.57 06/29/07
*/
package com.sun.messaging.jmq.jmsserver.pool;
import java.util.*;
import com.sun.messaging.jmq.jmsserver.Globals;
import com.sun.messaging.jmq.jmsserver.resources.*;
import com.sun.messaging.jmq.util.MQThread;
import com.sun.messaging.jmq.util.log.Logger;
/**
* This class implements a simple thread pool.
*
* This thread pool has a minimum and maximum number of threads. At creation, the minimum number of threads are created
* and "BasicRunnable" objects are assigned to the threads.
*
* If there are no available threads (thread count == max), the system will either wait until a thread is available OR
* throw an exception.
*
* As the load on the system decreases, if the thread count is greater than <B>min</b>, the threads will exit IF they
* have not been needed after a certain amount of time until the system is back down to <b>min</b>
* <P>
*
* @see Operation
* @see BasicRunnable
*
*/
public class ThreadPool {
// sync scheme:
// use lock for objects & counts
// use current -> for current
// use current -> for availIndx
// use available -> for available
// use this -> access to lists/wait->notify
//
// make copies for resume, destroy
// public Object lock = new Object(); // indexes and counts
public boolean destroyed = false;
private boolean in_destroy = false;
private static boolean DEBUG = false;
protected Logger logger = Globals.getLogger();
RunnableFactory runfac = null;
/**
* threads which have exited so their index can be reused threads exit when either they timeout OR a problem occurs
*/
LinkedHashSet availIndx = null;
/**
* list of all current threads/runnables
*/
ArrayList current = null; // XXX-LKS - may want to use a different list type
/**
* list of waiting runnables
*/
LinkedList available = null;
/**
* current indx for next thread created
*/
int nextThreadId = 0;
/**
* thread group for this thread pool
*/
protected ThreadGroup tgroup = null;
/**
* minimum number of threads
*/
protected int min;
/**
* maximum number of threads
*/
protected int max;
/**
* name of the thread
*/
protected String name = null;
protected int current_count = 0;
/**
* flag which indicates if all threads should "suspend" themselves. We dont want to truely suspend the threads because
* that is considered unsafe
*/
protected boolean notActive = true;
protected int priority = Thread.NORM_PRIORITY;
public boolean isValid() {
return !destroyed && !in_destroy;
}
public void setPriority(int p) {
this.priority = p;
}
/**
* retrieve the minimum # of threads
*/
public synchronized int getMinimum() {
return min;
}
/**
* retrieve the maximum # of threads
*/
public synchronized int getMaximum() {
return max;
}
/**
* set the minumum # of threads
*
* @throws IllegalArgumentException
*/
public synchronized void setMinimum(int num) {
setMinMax(num, max);
}
/**
* set the maximum # of threads
*
* @throws IllegalArgumentException
*/
public synchronized void setMaximum(int num) {
setMinMax(min, num);
}
public synchronized Hashtable getDebugState() {
Hashtable ht = new Hashtable();
ht.put("min", Integer.valueOf(min));
ht.put("max", Integer.valueOf(max));
ht.put("name", name);
ht.put("current_count", Integer.valueOf(current_count));
ht.put("nextThreadId", Integer.valueOf(nextThreadId));
ht.put("notActive", Boolean.valueOf(notActive));
ht.put("destroyed", Boolean.valueOf(destroyed));
ht.put("in_destroy", Boolean.valueOf(in_destroy));
ht.put("priority", Integer.valueOf(priority));
if (current != null) {
ht.put("currentCnt", Integer.valueOf(current.size()));
Vector v = new Vector();
Iterator itr = current.iterator();
while (itr.hasNext()) {
BasicRunnable runner = (BasicRunnable) itr.next();
if (runner == null) {
v.add("Runner is null");
} else {
v.add(runner.getDebugState());
}
}
ht.put("current", v);
} else {
ht.put("currentCnt", "null");
}
if (availIndx != null) {
ht.put("availIndxCnt", Integer.valueOf(availIndx.size()));
Vector v = new Vector();
Iterator itr = availIndx.iterator();
while (itr.hasNext()) {
Integer index = (Integer) itr.next();
v.add(index);
}
ht.put("availIndx", v);
} else {
ht.put("availIndxCnt", "null");
}
if (available != null) {
ht.put("availableCnt", Integer.valueOf(available.size()));
Vector v = new Vector();
Iterator itr = available.iterator();
while (itr.hasNext()) {
BasicRunnable runner = (BasicRunnable) itr.next();
v.add(runner.getDebugState());
}
ht.put("available", v);
} else {
ht.put("availableCnt", "null");
}
return ht;
}
/**
* @return int[0] - min; int[1] - max; -1 no change
*
* @throws IllegalArgumentException
*/
public synchronized int[] setMinMax(int newmin, int newmax) {
int[] rets = new int[2];
rets[0] = -1;
rets[1] = -1;
if (in_destroy) {
return rets; // nothing to do
}
if (newmin == -1) {
newmin = min;
}
if (newmax == -1) {
newmax = max;
}
if (newmin > newmax) {
String[] args = { name, String.valueOf(newmin), String.valueOf(newmax) };
String emsg = Globals.getBrokerResources().getKString(BrokerResources.W_THREADPOOL_MIN_GT_MAX_SET_MIN_TO_MAX, args);
logger.log(logger.WARNING, emsg);
newmin = newmax;
}
// OK first deal w/ destroying any threads over min
int count = current.size();
// now set the destroy behavior on existing threads
// greater than max
for (int i = newmax; i < max && i < count; i++) {
BasicRunnable runner = (BasicRunnable) current.get(i);
if (runner == null) {
continue;
}
runner.setThreadBehavior(BasicRunnable.B_DESTROY_THREAD);
}
// now turn off timeout behavior on threads above newmin
// && below min
for (int i = newmin; i > min && i > 0 && i < count; i--) {
BasicRunnable runner = (BasicRunnable) current.get(i);
if (runner == null) {
continue;
}
runner.setThreadBehavior(BasicRunnable.B_STAY_RUNNING);
}
// now turn on timeout behavior on threads > newmin
for (int i = newmin; i < max && i < count; i++) {
BasicRunnable runner = (BasicRunnable) current.get(i);
if (runner == null) {
continue;
}
runner.setThreadBehavior(BasicRunnable.B_TIMEOUT_THREAD);
}
// finally, redo the list of available indexes
LinkedHashSet list = new LinkedHashSet();
for (int i = 0; i < count; i++) {
Object obj = current.get(i);
if (obj == null) {
list.add(Integer.valueOf(i));
}
}
// set the values
if (min != newmin) {
min = newmin;
rets[0] = min;
}
if (max != newmax) {
max = newmax;
rets[1] = max;
}
availIndx = list;
return rets;
}
public synchronized void debug() {
StringBuilder info = new StringBuilder();
info.append("\n--------------------------------------------\n DUMPING THREAD POOL ").append(this)
.append("\n--------------------------------------------\n[min, max] = [").append(min).append(',').append(max)
.append("]\n---- threads ----\n#\tAvailable\thash\tRunner\n");
for (int i = 0; i < max; i++) {
BasicRunnable runner = null;
if (i < current.size()) {
runner = (BasicRunnable) current.get(i);
}
if (runner != null) {
info.append(i).append('\t').append(available.contains(runner)).append('\t').append(Long.toHexString(runner.hashCode())).append('\t')
.append(runner).append('\n');
} else {
continue;
}
}
info.append("--------------------------------------------\n" + "DONE DUMPING THREAD POOL\n" + "--------------------------------------------\n\n");
logger.log(Logger.DEBUG, info.toString());
}
/**
* returns the current number of "threads" in the thread pool
*/
public synchronized int getThreadNum() {
return current_count;
}
/**
* returns the # of assigned threads
*/
public synchronized int getAssignedCnt() {
return current_count - available.size() - availIndx.size();
}
/**
* Create a thread pool of the passed in name with a minimum and maximum number of threads.
*
* @param name the name of the thread pool
* @param min the minimum number of threads
* @param max the maximum number of threads
*/
public ThreadPool(String name, int min, int max, RunnableFactory runfac) {
if (DEBUG) {
String args[] = { name, String.valueOf(min), String.valueOf(max) };
logger.log(Logger.DEBUG, "ThreadPool: Creating Thread Pool({0}) = [ {1}, {2} ]", args);
}
this.min = min;
this.max = max;
tgroup = new MyThreadGroup("ThreadPool(" + name + ")");
this.name = name;
availIndx = new LinkedHashSet();
current = new ArrayList();
available = new LinkedList();
this.runfac = runfac;
this.current_count = 0;
this.nextThreadId = 0;
}
/**
* start threads operation. By default, when the thread pool is created, the notActive flag is true, so the threads are
* not operating
*/
public void start() {
// for now .. does the same as resume
resume();
}
/**
* retrieve the state of the notActive flag
*
* @return the notActive flag
*/
public synchronized boolean isSuspended() {
return notActive;
}
// suspending doesnt happen immediately .. the current operation
// WILL complete before the pool is suspended
//
/**
* suspend threads operation.
* <P>
* Threads will <B>not</B> be immediately suspended, instead they will go into a "wait" state as soon as they finish
* processing the current operation.
*
* This method is not synchronized, because we dont really care what the state of the flag is at a given time .. it will
* always be picked up on the next iteration of the run method.
*/
public void suspend() {
if (DEBUG) {
logger.log(Logger.DEBUG, "ThreadPool: SUSPENDING ThreadPool({0})", name);
}
if (in_destroy) {
return; // nothing to do
}
notActive = true;
ArrayList copy = null;
synchronized (this) {
copy = new ArrayList(current);
}
for (int i = 0; i < copy.size(); i++) {
BasicRunnable runner = (BasicRunnable) copy.get(i);
if (runner != null) {
runner.suspend();
}
}
}
/**
* resume threads operation.
* <P>
* Threads will notified (which will wake them up) and then the threads will continue operation
*/
public void resume() {
if (DEBUG) {
logger.log(Logger.DEBUG, "ThreadPool: RESUMING ThreadPool({0})", name);
}
if (in_destroy) {
return; // nothing to do
}
notActive = false;
ArrayList copy = null;
synchronized (this) {
copy = new ArrayList(current);
}
for (int i = 0; i < copy.size(); i++) {
BasicRunnable runner = (BasicRunnable) copy.get(i);
if (runner != null) {
runner.resume();
}
}
synchronized (this) {
notifyAll(); // wake everyone up
}
}
/**
* suspends or resume threads operation.
* <P>
* This just calls the appropriate suspend() or resume() operation.
*
* @see #suspend
* @see #resume
*
* @param susp true if the pool should be suspended, false if the thread pool should be resumed
*/
public void setSuspended(boolean susp) {
if (susp) {
suspend();
} else {
resume();
}
}
// XXX
/**
* get a runnable to use (its assigned when returned)
*/
public BasicRunnable getAvailRunnable(boolean wait) {
try {
BasicRunnable runner = null;
String how = null;
while (!in_destroy && !destroyed) { // wait until something available
synchronized (this) {
if (!available.isEmpty()) {
how = "availableList";
runner = (BasicRunnable) available.removeFirst();
} else if (!availIndx.isEmpty()) {
how = "existing index";
Iterator itr = availIndx.iterator();
int indx = ((Integer) itr.next()).intValue();
itr.remove();
runner = createNewThread(indx);
} else if (nextThreadId < max) {
how = "new thread";
int indx = nextThreadId;
nextThreadId++;
runner = createNewThread(indx);
} else {
return null; // nothing available
}
}
if (runner == null) {
logger.log(Logger.ERROR, BrokerResources.E_INTERNAL_BROKER_ERROR, how);
continue;
}
synchronized (runner) {
if (runner.available()) {
runner.setState(BasicRunnable.RUN_PREASSIGNED);
} else { // getting destroyed
runner = null;
}
}
if (runner != null) {
break;
}
synchronized (this) {
if (wait) {
try {
wait();
} catch (InterruptedException ex) {
break;
}
} else {
break;
}
}
}
return runner;
} catch (Exception ex) {
logger.logStack(logger.WARNING, ex.getMessage(), ex);
return null;
}
}
/**
* create a new thread and add it to the thread list
*
* @throws ArrayIndexOutOfBoundsException if max threads has been reached
*/
private synchronized BasicRunnable createNewThread(int indx) {
if (indx >= max) {
throw new ArrayIndexOutOfBoundsException(
Globals.getBrokerResources().getString(BrokerResources.X_INTERNAL_EXCEPTION, "Too many threads " + current_count + "," + max));
}
BasicRunnable runner = null;
if (indx < current.size()) { // get current if possible
runner = (BasicRunnable) current.get(indx);
}
if (runner == null) {
runner = runfac.getRunnable(indx, this);
if (current.size() <= indx) {
current.add(indx, runner);
} else {
current.set(indx, runner);
}
}
runner.setState(BasicRunnable.RUN_READY);
Thread thr = new MQThread(tgroup, runner, "Thread-" + name + "[" + indx + "]");
thr.setPriority(priority);
if (indx >= min) {
runner.setThreadBehavior(BasicRunnable.B_TIMEOUT_THREAD);
}
current_count++;
thr.start();
return runner;
}
public synchronized void runnableDestroying(int indx) {
if (indx >= current.size()) {
logger.log(Logger.ERROR, BrokerResources.E_INTERNAL_BROKER_ERROR, " attempting to destroy unknown thread " + indx);
debug();
return;
}
BasicRunnable r = (BasicRunnable) current.get(indx);
current.set(indx, null);
available.remove(r);
}
public synchronized void runnableExit(int indx) {
if (in_destroy) {
return; // nothing to do
}
current_count--;
if (indx < min) {
// recreate
BasicRunnable runner = createNewThread(indx);
available.add(runner);
} else { // put on possibly recreate list
if (indx > max) {
// ignore
} else { // stick on list
availIndx.add(Integer.valueOf(indx));
}
}
notifyAll();
}
public synchronized void releaseRunnable(BasicRunnable run) {
if (in_destroy) {
return; // nothing to do
}
if (run == null) {
logger.log(Logger.WARNING, BrokerResources.E_INTERNAL_BROKER_ERROR, "null basic runnable " + run);
return;
}
// XXX - add logic for handling min/max
int indx = run.getId();
if (indx < min) { // put at front of list
// XXX - DEBUG
if (!available.contains(run)) {
available.addFirst(run);
}
} else { // put at back of list
if (!available.contains(run)) {
available.addLast(run);
}
}
notifyAll();
}
/**
* cleanly stops threads and destroys
*/
public void destroy() {
ArrayList copy = null;
synchronized (this) {
in_destroy = true; // prevents new threads
copy = new ArrayList(current);
}
for (int i = 0; i < copy.size(); i++) {
BasicRunnable runner = (BasicRunnable) copy.get(i);
if (runner != null) {
runner.destroy();
}
}
}
public void waitOnDestroy(long timeout) {
destroy();
ArrayList copy = null;
synchronized (this) {
copy = new ArrayList(current);
}
for (int i = 0; i < copy.size(); i++) {
BasicRunnable runner = (BasicRunnable) copy.get(i);
if (runner == null) {
continue;
}
if (runner.isBusy()) {
runner.waitOnDestroy(timeout);
}
if (!runner.isDestroyed() && runner.isCritical()) {
logger.log(Logger.WARNING, BrokerResources.W_CANNOT_DESTROY_OPERATION, runner, String.valueOf(timeout));
}
}
destroyed = true;
synchronized (this) {
notifyAll();
}
}
public void handleException(Throwable thr) {
logger.logStack(Logger.WARNING, BrokerResources.E_INTERNAL_BROKER_ERROR, "Unexpected Exception or Error", thr);
}
/**
* this subclass of ThreadGroup handles making sure any exception is correctly handled
*
* IF the exception is thread death .. the system will decide whether or not to recreate the thread
*
* the exception/Error will always be logged
*
*/
public static class MyThreadGroup extends ThreadGroup {
public MyThreadGroup(String name) {
super(name);
}
@Override
public void uncaughtException(Thread t, Throwable thr) {
// notify ThreadPool that the thread is gone
Globals.handleGlobalError(thr, "Unexpected thread pool error");
}
}
}