-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathEnhancedQueueExecutor.java
3369 lines (3011 loc) · 131 KB
/
EnhancedQueueExecutor.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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.jboss.threads;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Thread.currentThread;
import static java.security.AccessController.doPrivileged;
import static java.security.AccessController.getContext;
import static java.util.concurrent.locks.LockSupport.parkNanos;
import static java.util.concurrent.locks.LockSupport.unpark;
import static org.jboss.threads.JBossExecutors.unsafe;
import java.lang.management.ManagementFactory;
import java.security.AccessControlContext;
import java.security.PrivilegedAction;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import org.jboss.threads.management.ManageableThreadPoolExecutorService;
import org.jboss.threads.management.StandardThreadPoolMXBean;
import org.wildfly.common.Assert;
import org.wildfly.common.cpu.ProcessorInfo;
/**
* A task-or-thread queue backed thread pool executor service. Tasks are added in a FIFO manner, and consumers in a LIFO manner.
* Threads are only ever created in the event that there are no idle threads available to service a task, which, when
* combined with the LIFO-based consumer behavior, means that the thread pool will generally trend towards the minimum
* necessary size. In addition, the optional {@linkplain #setGrowthResistance(float) growth resistance feature} can
* be used to further govern the thread pool size.
* <p>
* Additionally, this thread pool implementation supports scheduling of tasks.
* The scheduled tasks will execute on the main pool.
* <p>
* New instances of this thread pool are created by constructing and configuring a {@link Builder} instance, and calling
* its {@link Builder#build() build()} method.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class EnhancedQueueExecutor extends EnhancedQueueExecutorBase6 implements ManageableThreadPoolExecutorService, ScheduledExecutorService {
private static final Thread[] NO_THREADS = new Thread[0];
static {
Version.getVersionString();
MBeanUnregisterAction.forceInit();
}
/*
┌──────────────────────────┐
│ Explanation of operation │
└──────────────────────────┘
The primary mechanism of this executor is the special linked list/stack. This list has the following properties:
• Multiple node types:
◦ Task nodes (TaskNode), which have the following properties:
▪ Strongly connected (no task is ever removed from the middle of the list; tail can always be found by following .next pointers)
▪ FIFO (insertion at tail.next, "removal" at head.next)
▪ Head and tail always refer to TaskNodes; head.next/tail.next are the "true" action points for all node types
▪ At least one dead task node is always in the list, thus the task is cleared after execution to avoid leaks
◦ Waiting consumer thread nodes (PoolThreadNode), which have the following properties:
▪ LIFO/FILO (insertion and removal at tail.next)
▪ Carrier for task handoff between producer and waiting consumer
◦ Waiting termination (awaitTermination) thread nodes (TerminateWaiterNode), which have the following properties:
▪ Append-only (insertion at tail.next.next...next)
▪ All removed at once when termination is complete
▪ If a thread stops waiting, the node remains (but its thread field is cleared to prevent (best-effort) useless unparks)
▪ Once cleared, the thread field can never be reinitialized
• Concurrently accessed (multiple threads may read the list and update the head and tail pointers)
• TaskNode.next may be any node type or null
• PoolThreadNode.next may only be another PoolThreadNode or null
• TerminateWaiterNode.next may only be another TerminateWaiterNode or null
The secondary mechanism is the thread status atomic variable. It is logically a structure with the following fields:
• Current thread count (currentSizeOf(), withCurrentSize())
• Core pool size (coreSizeOf(), withCoreSize())
• Max pool size (maxSizeOf(), withMaxSize())
• Shutdown-requested flag (isShutdownRequested(), withShutdownRequested())
• Shutdown-with-interrupt requested flag (isShutdownInterrupt(), withShutdownInterrupt())
• Shutdown-completed flag (isShutdownComplete(), withShutdownComplete())
• The decision to create a new thread is affected by whether the number of active threads is less than the core size;
if not, then the growth resistance factor is applied to decide whether the task should be enqueued or a new thread begun.
Note: the default growth resistance factor is 0% resistance.
The final mechanism is the queue status atomic variable. It is logically a structure with the following fields:
• Current queue size (currentQueueSizeOf(), withCurrentQueueSize())
• Queue size limit (maxQueueSizeOf(), withMaxQueueSize())
*/
// =======================================================
// Optimization control flags
// =======================================================
/**
* A global hint which establishes whether it is recommended to disable uses of {@code EnhancedQueueExecutor}.
* This hint defaults to {@code false} but can be changed to {@code true} by setting the {@code jboss.threads.eqe.disable}
* property to {@code true} before this class is initialized.
*/
public static final boolean DISABLE_HINT = readBooleanPropertyPrefixed("disable", false);
/**
* Update the summary statistics.
*/
static final boolean UPDATE_STATISTICS = readBooleanPropertyPrefixed("statistics", false);
/**
* Maintain an estimate of the number of threads which are currently doing work on behalf of the thread pool.
*/
static final boolean UPDATE_ACTIVE_COUNT =
UPDATE_STATISTICS || readBooleanPropertyPrefixed("statistics.active-count", false);
/**
* Suppress queue limit and size tracking for performance.
*/
static final boolean NO_QUEUE_LIMIT = readBooleanPropertyPrefixed("unlimited-queue", false);
/**
* Set the default value for whether an mbean is to be auto-registered for the thread pool.
*/
static final boolean REGISTER_MBEAN = readBooleanPropertyPrefixed("register-mbean", true);
/**
* Set to enable or disable MBean registration.
*/
static final boolean DISABLE_MBEAN = readBooleanPropertyPrefixed("disable-mbean", readProperty("org.graalvm.nativeimage.imagecode", null) != null);
/**
* The number of times a thread should spin/yield before actually parking.
*/
static final int PARK_SPINS = readIntPropertyPrefixed("park-spins", ProcessorInfo.availableProcessors() == 1 ? 0 : 1 << 7);
/**
* The yield ratio expressed as the number of spins that should yield.
*/
static final int YIELD_FACTOR = max(min(readIntPropertyPrefixed("park-yields", 1), PARK_SPINS), 0);
// =======================================================
// Constants
// =======================================================
static final Executor DEFAULT_HANDLER = JBossExecutors.rejectingExecutor();
// =======================================================
// Immutable configuration fields
// =======================================================
/**
* The thread factory.
*/
private final ThreadFactory threadFactory;
/**
* The approximate set of pooled threads.
*/
private final Set<Thread> runningThreads = Collections.newSetFromMap(new ConcurrentHashMap<>());
/**
* The management bean instance.
*/
private final MXBeanImpl mxBean;
/**
* The MBean registration handle (if any).
*/
private final Object handle;
/**
* The access control context of the creating thread.
* Will be set to null when the MBean is not registered.
*/
private volatile AccessControlContext acc;
/**
* The context handler for the user-defined context.
*/
private final ContextHandler<?> contextHandler;
/**
* The task for scheduled execution.
*/
private final SchedulerTask schedulerTask = new SchedulerTask();
/**
* The scheduler thread.
*/
private final Thread schedulerThread;
// =======================================================
// Current state fields
// =======================================================
/**
* The linked list of threads waiting for termination of this thread pool.
*/
@SuppressWarnings("unused") // used by field updater
volatile Waiter terminationWaiters;
/**
* Queue size:
* <ul>
* <li>Bit 00..1F: current queue length</li>
* <li>Bit 20..3F: queue limit</li>
* </ul>
*/
@SuppressWarnings("unused") // used by field updater
volatile long queueSize;
/**
* The thread keep-alive timeout value.
*/
volatile long timeoutNanos;
/**
* A resistance factor applied after the core pool is full; values applied here will cause that fraction
* of submissions to create new threads when no idle thread is available. A value of {@code 0.0f} implies that
* threads beyond the core size should be created as aggressively as threads within it; a value of {@code 1.0f}
* implies that threads beyond the core size should never be created.
*/
volatile float growthResistance;
/**
* The handler for tasks which cannot be accepted by the executor.
*/
volatile Executor handoffExecutor;
/**
* The handler for uncaught exceptions which occur during user tasks.
*/
volatile Thread.UncaughtExceptionHandler exceptionHandler;
/**
* The termination task to execute when the thread pool exits.
*/
volatile Runnable terminationTask;
// =======================================================
// Statistics fields and counters
// =======================================================
/**
* The peak number of threads ever created by this pool.
*/
@SuppressWarnings("unused") // used by field updater
volatile int peakThreadCount;
/**
* The approximate peak queue size.
*/
@SuppressWarnings("unused") // used by field updater
volatile int peakQueueSize;
private final LongAdder submittedTaskCounter = new LongAdder();
private final LongAdder completedTaskCounter = new LongAdder();
private final LongAdder rejectedTaskCounter = new LongAdder();
private final LongAdder spinMisses = new LongAdder();
/**
* The current active number of threads.
*/
@SuppressWarnings("unused")
volatile int activeCount;
// =======================================================
// Updaters
// =======================================================
private static final long terminationWaitersOffset;
private static final long queueSizeOffset;
private static final long peakThreadCountOffset;
private static final long activeCountOffset;
private static final long peakQueueSizeOffset;
static {
try {
terminationWaitersOffset = unsafe.objectFieldOffset(EnhancedQueueExecutor.class.getDeclaredField("terminationWaiters"));
queueSizeOffset = unsafe.objectFieldOffset(EnhancedQueueExecutor.class.getDeclaredField("queueSize"));
peakThreadCountOffset = unsafe.objectFieldOffset(EnhancedQueueExecutor.class.getDeclaredField("peakThreadCount"));
activeCountOffset = unsafe.objectFieldOffset(EnhancedQueueExecutor.class.getDeclaredField("activeCount"));
peakQueueSizeOffset = unsafe.objectFieldOffset(EnhancedQueueExecutor.class.getDeclaredField("peakQueueSize"));
} catch (NoSuchFieldException e) {
throw new NoSuchFieldError(e.getMessage());
}
}
// =======================================================
// Thread state field constants
// =======================================================
private static final long TS_THREAD_CNT_MASK = 0b1111_1111_1111_1111_1111L; // 20 bits, can be shifted as needed
// shift amounts
private static final long TS_CURRENT_SHIFT = 0;
private static final long TS_CORE_SHIFT = 20;
private static final long TS_MAX_SHIFT = 40;
private static final long TS_ALLOW_CORE_TIMEOUT = 1L << 60;
private static final long TS_SHUTDOWN_REQUESTED = 1L << 61;
private static final long TS_SHUTDOWN_INTERRUPT = 1L << 62;
@SuppressWarnings("NumericOverflow")
private static final long TS_SHUTDOWN_COMPLETE = 1L << 63;
private static final int EXE_OK = 0;
private static final int EXE_REJECT_QUEUE_FULL = 1;
private static final int EXE_REJECT_SHUTDOWN = 2;
private static final int EXE_CREATE_THREAD = 3;
private static final int AT_YES = 0;
private static final int AT_NO = 1;
private static final int AT_SHUTDOWN = 2;
// =======================================================
// Marker objects
// =======================================================
static final QNode TERMINATE_REQUESTED = new TerminateWaiterNode();
static final QNode TERMINATE_COMPLETE = new TerminateWaiterNode();
static final Waiter TERMINATE_COMPLETE_WAITER = new Waiter(null);
static final Runnable WAITING = new NullRunnable();
static final Runnable GAVE_UP = new NullRunnable();
static final Runnable ACCEPTED = new NullRunnable();
static final Runnable EXIT = new NullRunnable();
// =======================================================
// Constructor
// =======================================================
static final AtomicInteger sequence = new AtomicInteger(1);
EnhancedQueueExecutor(final Builder builder) {
super();
int maxSize = builder.getMaximumPoolSize();
int coreSize = min(builder.getCorePoolSize(), maxSize);
this.handoffExecutor = builder.getHandoffExecutor();
this.exceptionHandler = builder.getExceptionHandler();
this.threadFactory = builder.getThreadFactory();
this.schedulerThread = threadFactory.newThread(schedulerTask);
String schedulerName = this.schedulerThread.getName();
this.schedulerThread.setName(schedulerName + " (scheduler)");
this.terminationTask = builder.getTerminationTask();
this.growthResistance = builder.getGrowthResistance();
this.contextHandler = builder.getContextHandler();
final Duration keepAliveTime = builder.getKeepAliveTime();
// initial dead node
// thread stat
threadStatus = withCoreSize(withMaxSize(withAllowCoreTimeout(0L, builder.allowsCoreThreadTimeOut()), maxSize), coreSize);
timeoutNanos = TimeUtil.clampedPositiveNanos(keepAliveTime);
queueSize = withMaxQueueSize(withCurrentQueueSize(0L, 0), builder.getMaximumQueueSize());
mxBean = new MXBeanImpl();
if (! DISABLE_MBEAN && builder.isRegisterMBean()) {
this.acc = getContext();
final String configuredName = builder.getMBeanName();
final String finalName = configuredName != null ? configuredName : "threadpool-" + sequence.getAndIncrement();
handle = doPrivileged(new MBeanRegisterAction(finalName, mxBean), acc);
} else {
handle = null;
this.acc = null;
}
}
static final class MBeanRegisterAction implements PrivilegedAction<ObjectInstance> {
private final String finalName;
private final MXBeanImpl mxBean;
MBeanRegisterAction(final String finalName, final MXBeanImpl mxBean) {
this.finalName = finalName;
this.mxBean = mxBean;
}
public ObjectInstance run() {
try {
final Hashtable<String, String> table = new Hashtable<>();
table.put("name", ObjectName.quote(finalName));
table.put("type", "thread-pool");
return ManagementFactory.getPlatformMBeanServer().registerMBean(mxBean, new ObjectName("jboss.threads", table));
} catch (Throwable ignored) {
}
return null;
}
}
// =======================================================
// Builder
// =======================================================
/**
* The builder class for an {@code EnhancedQueueExecutor}. All the fields are initialized to sensible defaults for
* a small thread pool.
*/
public static final class Builder {
private ThreadFactory threadFactory = Executors.defaultThreadFactory();
private Runnable terminationTask = NullRunnable.getInstance();
private Executor handoffExecutor = DEFAULT_HANDLER;
private Thread.UncaughtExceptionHandler exceptionHandler = JBossExecutors.loggingExceptionHandler();
private int coreSize = 16;
private int maxSize = 64;
private Duration keepAliveTime = Duration.ofSeconds(30);
private float growthResistance;
private boolean allowCoreTimeOut;
private int maxQueueSize = Integer.MAX_VALUE;
private boolean registerMBean = REGISTER_MBEAN;
private String mBeanName;
private ContextHandler<?> contextHandler = ContextHandler.NONE;
/**
* Construct a new instance.
*/
public Builder() {}
/**
* Get the configured thread factory.
*
* @return the configured thread factory (not {@code null})
*/
public ThreadFactory getThreadFactory() {
return threadFactory;
}
/**
* Set the configured thread factory.
*
* @param threadFactory the configured thread factory (must not be {@code null})
* @return this builder
*/
public Builder setThreadFactory(final ThreadFactory threadFactory) {
Assert.checkNotNullParam("threadFactory", threadFactory);
this.threadFactory = threadFactory;
return this;
}
/**
* Get the termination task. By default, an empty {@code Runnable} is used.
*
* @return the termination task (not {@code null})
*/
public Runnable getTerminationTask() {
return terminationTask;
}
/**
* Set the termination task.
*
* @param terminationTask the termination task (must not be {@code null})
* @return this builder
*/
public Builder setTerminationTask(final Runnable terminationTask) {
Assert.checkNotNullParam("terminationTask", terminationTask);
this.terminationTask = terminationTask;
return this;
}
/**
* Get the core pool size. This is the size below which new threads will always be created if no idle threads
* are available. If the pool size reaches the core size but has not yet reached the maximum size, a resistance
* factor will be applied to each task submission which determines whether the task should be queued or a new
* thread started.
*
* @return the core pool size
* @see EnhancedQueueExecutor#getCorePoolSize()
*/
public int getCorePoolSize() {
return coreSize;
}
/**
* Set the core pool size. If the configured maximum pool size is less than the configured core size, the
* core size will be reduced to match the maximum size when the thread pool is constructed.
*
* @param coreSize the core pool size (must be greater than or equal to 0, and less than 2^20)
* @return this builder
* @see EnhancedQueueExecutor#setCorePoolSize(int)
*/
public Builder setCorePoolSize(final int coreSize) {
Assert.checkMinimumParameter("coreSize", 0, coreSize);
Assert.checkMaximumParameter("coreSize", TS_THREAD_CNT_MASK, coreSize);
this.coreSize = coreSize;
return this;
}
/**
* Get the maximum pool size. This is the absolute upper limit to the size of the thread pool.
*
* @return the maximum pool size
* @see EnhancedQueueExecutor#getMaximumPoolSize()
*/
public int getMaximumPoolSize() {
return maxSize;
}
/**
* Set the maximum pool size. If the configured maximum pool size is less than the configured core size, the
* core size will be reduced to match the maximum size when the thread pool is constructed.
*
* @param maxSize the maximum pool size (must be greater than or equal to 0, and less than 2^20)
* @return this builder
* @see EnhancedQueueExecutor#setMaximumPoolSize(int)
*/
public Builder setMaximumPoolSize(final int maxSize) {
Assert.checkMinimumParameter("maxSize", 0, maxSize);
Assert.checkMaximumParameter("maxSize", TS_THREAD_CNT_MASK, maxSize);
this.maxSize = maxSize;
return this;
}
/**
* Get the thread keep-alive time. This is the amount of time (in the configured time unit) that idle threads
* will wait for a task before exiting.
*
* @return the thread keep-alive time duration
*/
public Duration getKeepAliveTime() {
return keepAliveTime;
}
/**
* Get the thread keep-alive time. This is the amount of time (in the configured time unit) that idle threads
* will wait for a task before exiting.
*
* @param keepAliveUnits the time keepAliveUnits of the keep-alive time (must not be {@code null})
* @return the thread keep-alive time
* @see EnhancedQueueExecutor#getKeepAliveTime(TimeUnit)
* @deprecated Use {@link #getKeepAliveTime()} instead.
*/
@Deprecated
public long getKeepAliveTime(TimeUnit keepAliveUnits) {
Assert.checkNotNullParam("keepAliveUnits", keepAliveUnits);
final long secondsPart = keepAliveUnits.convert(keepAliveTime.getSeconds(), TimeUnit.SECONDS);
final long nanoPart = keepAliveUnits.convert(keepAliveTime.getNano(), TimeUnit.NANOSECONDS);
final long sum = secondsPart + nanoPart;
return sum < 0 ? Long.MAX_VALUE : sum;
}
/**
* Set the thread keep-alive time.
*
* @param keepAliveTime the thread keep-alive time (must not be {@code null})
*/
public Builder setKeepAliveTime(final Duration keepAliveTime) {
Assert.checkNotNullParam("keepAliveTime", keepAliveTime);
this.keepAliveTime = keepAliveTime;
return this;
}
/**
* Set the thread keep-alive time.
*
* @param keepAliveTime the thread keep-alive time (must be greater than 0)
* @param keepAliveUnits the time keepAliveUnits of the keep-alive time (must not be {@code null})
* @return this builder
* @see EnhancedQueueExecutor#setKeepAliveTime(long, TimeUnit)
* @deprecated Use {@link #setKeepAliveTime(Duration)} instead.
*/
@Deprecated
public Builder setKeepAliveTime(final long keepAliveTime, final TimeUnit keepAliveUnits) {
Assert.checkMinimumParameter("keepAliveTime", 1L, keepAliveTime);
Assert.checkNotNullParam("keepAliveUnits", keepAliveUnits);
this.keepAliveTime = Duration.of(keepAliveTime, JDKSpecific.timeToTemporal(keepAliveUnits));
return this;
}
/**
* Get the thread pool growth resistance. This is the average fraction of submitted tasks that will be enqueued (instead
* of causing a new thread to start) when there are no idle threads and the pool size is equal to or greater than
* the core size (but still less than the maximum size). A value of {@code 0.0} indicates that tasks should
* not be enqueued until the pool is completely full; a value of {@code 1.0} indicates that tasks should always
* be enqueued until the queue is completely full.
*
* @return the thread pool growth resistance
* @see EnhancedQueueExecutor#getGrowthResistance()
*/
public float getGrowthResistance() {
return growthResistance;
}
/**
* Set the thread pool growth resistance.
*
* @param growthResistance the thread pool growth resistance (must be in the range {@code 0.0f ≤ n ≤ 1.0f})
* @return this builder
* @see #getGrowthResistance()
* @see EnhancedQueueExecutor#setGrowthResistance(float)
*/
public Builder setGrowthResistance(final float growthResistance) {
Assert.checkMinimumParameter("growthResistance", 0.0f, growthResistance);
Assert.checkMaximumParameter("growthResistance", 1.0f, growthResistance);
this.growthResistance = growthResistance;
return this;
}
/**
* Determine whether core threads are allowed to time out. A "core thread" is defined as any thread in the pool
* when the pool size is below the pool's {@linkplain #getCorePoolSize() core pool size}.
*
* @return {@code true} if core threads are allowed to time out, {@code false} otherwise
* @see EnhancedQueueExecutor#allowsCoreThreadTimeOut()
*/
public boolean allowsCoreThreadTimeOut() {
return allowCoreTimeOut;
}
/**
* Establish whether core threads are allowed to time out. A "core thread" is defined as any thread in the pool
* when the pool size is below the pool's {@linkplain #getCorePoolSize() core pool size}.
*
* @param allowCoreTimeOut {@code true} if core threads are allowed to time out, {@code false} otherwise
* @return this builder
* @see EnhancedQueueExecutor#allowCoreThreadTimeOut(boolean)
*/
public Builder allowCoreThreadTimeOut(final boolean allowCoreTimeOut) {
this.allowCoreTimeOut = allowCoreTimeOut;
return this;
}
/**
* Get the maximum queue size. If the queue is full and a task cannot be immediately accepted, rejection will result.
*
* @return the maximum queue size
* @see EnhancedQueueExecutor#getMaximumQueueSize()
*/
public int getMaximumQueueSize() {
return maxQueueSize;
}
/**
* Set the maximum queue size.
* This has no impact when {@code jboss.threads.eqe.unlimited-queue} is set.
*
* @param maxQueueSize the maximum queue size (must be ≥ 0)
* @return this builder
* @see EnhancedQueueExecutor#setMaximumQueueSize(int)
*/
public Builder setMaximumQueueSize(final int maxQueueSize) {
Assert.checkMinimumParameter("maxQueueSize", 0, maxQueueSize);
Assert.checkMaximumParameter("maxQueueSize", Integer.MAX_VALUE, maxQueueSize);
this.maxQueueSize = maxQueueSize;
return this;
}
/**
* Get the handoff executor.
*
* @return the handoff executor (not {@code null})
*/
public Executor getHandoffExecutor() {
return handoffExecutor;
}
/**
* Set the handoff executor.
*
* @param handoffExecutor the handoff executor (must not be {@code null})
* @return this builder
*/
public Builder setHandoffExecutor(final Executor handoffExecutor) {
Assert.checkNotNullParam("handoffExecutor", handoffExecutor);
this.handoffExecutor = handoffExecutor;
return this;
}
/**
* Get the uncaught exception handler.
*
* @return the uncaught exception handler (not {@code null})
*/
public Thread.UncaughtExceptionHandler getExceptionHandler() {
return exceptionHandler;
}
/**
* Set the uncaught exception handler.
*
* @param exceptionHandler the uncaught exception handler (must not be {@code null})
* @return this builder
*/
public Builder setExceptionHandler(final Thread.UncaughtExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
/**
* Construct the executor from the configured parameters.
*
* @return the executor, which will be active and ready to accept tasks (not {@code null})
*/
public EnhancedQueueExecutor build() {
return new EnhancedQueueExecutor(this);
}
/**
* Determine whether an MBean should automatically be registered for this pool.
*
* @return {@code true} if an MBean is to be auto-registered; {@code false} otherwise
*/
public boolean isRegisterMBean() {
return registerMBean;
}
/**
* Establish whether an MBean should automatically be registered for this pool.
*
* @param registerMBean {@code true} if an MBean is to be auto-registered; {@code false} otherwise
* @return this builder
*/
public Builder setRegisterMBean(final boolean registerMBean) {
this.registerMBean = registerMBean;
return this;
}
/**
* Get the overridden MBean name.
*
* @return the overridden MBean name, or {@code null} if a default name should be generated
*/
public String getMBeanName() {
return mBeanName;
}
/**
* Set the overridden MBean name.
*
* @param mBeanName the overridden MBean name, or {@code null} if a default name should be generated
* @return this builder
*/
public Builder setMBeanName(final String mBeanName) {
this.mBeanName = mBeanName;
return this;
}
/**
* Get the context handler for the user-defined context.
*
* @return the context handler for the user-defined context (not {@code null})
*/
public ContextHandler<?> getContextHandler() {
return contextHandler;
}
/**
* Set the context handler for the user-defined context.
*
* @param contextHandler the context handler for the user-defined context
* @return this builder
*/
public Builder setContextHandler(final ContextHandler<?> contextHandler) {
Assert.checkNotNullParam("contextHandler", contextHandler);
this.contextHandler = contextHandler;
return this;
}
}
// =======================================================
// ExecutorService
// =======================================================
/**
* Execute a task.
*
* @param runnable the task to execute (must not be {@code null})
*/
public void execute(Runnable runnable) {
Assert.checkNotNullParam("runnable", runnable);
final Task realRunnable = new Task(runnable, contextHandler.captureContext());
int result;
result = tryExecute(realRunnable);
boolean ok = false;
if (result == EXE_OK) {
// last check to ensure that there is at least one existent thread to avoid rare thread timeout race condition
if (currentSizeOf(threadStatus) == 0 && tryAllocateThread(0.0f) == AT_YES && ! doStartThread(null)) {
deallocateThread();
}
if (UPDATE_STATISTICS) submittedTaskCounter.increment();
return;
} else if (result == EXE_CREATE_THREAD) try {
ok = doStartThread(realRunnable);
} finally {
if (! ok) deallocateThread();
} else {
if (UPDATE_STATISTICS) rejectedTaskCounter.increment();
if (result == EXE_REJECT_SHUTDOWN) {
rejectShutdown(realRunnable);
} else {
assert result == EXE_REJECT_QUEUE_FULL;
rejectQueueFull(realRunnable);
}
}
}
/**
* Request that shutdown be initiated for this thread pool. This is equivalent to calling
* {@link #shutdown(boolean) shutdown(false)}; see that method for more information.
*/
public void shutdown() {
shutdown(false);
}
/**
* Attempt to stop the thread pool immediately by interrupting all running threads and de-queueing all pending
* tasks. The thread pool might not be fully stopped when this method returns, if a currently running task
* does not respect interruption.
*
* @return a list of pending tasks (not {@code null})
*/
public List<Runnable> shutdownNow() {
shutdown(true);
final ArrayList<Runnable> list = new ArrayList<>();
TaskNode head = this.head;
QNode headNext;
for (;;) {
headNext = head.getNext();
if (headNext == head) {
// a racing consumer has already consumed it (and moved head)
head = this.head;
continue;
}
if (headNext instanceof TaskNode) {
TaskNode taskNode = (TaskNode) headNext;
if (compareAndSetHead(head, taskNode)) {
// save from GC nepotism
head.setNextOrdered(head);
if (! NO_QUEUE_LIMIT) decreaseQueueSize();
head = taskNode;
list.add(taskNode.task.handoff());
}
// retry
} else {
// no more tasks;
return list;
}
}
}
/**
* Determine whether shutdown was requested on this thread pool.
*
* @return {@code true} if shutdown was requested, {@code false} otherwise
*/
public boolean isShutdown() {
return isShutdownRequested(threadStatus);
}
/**
* Determine whether shutdown has completed on this thread pool.
*
* @return {@code true} if shutdown has completed, {@code false} otherwise
*/
public boolean isTerminated() {
return isShutdownComplete(threadStatus);
}
/**
* Wait for the thread pool to complete termination. If the timeout expires before the thread pool is terminated,
* {@code false} is returned. If the calling thread is interrupted before the thread pool is terminated, then
* an {@link InterruptedException} is thrown.
*
* @param timeout the amount of time to wait (must be ≥ 0)
* @param unit the unit of time to use for waiting (must not be {@code null})
* @return {@code true} if the thread pool terminated within the given timeout, {@code false} otherwise
* @throws InterruptedException if the calling thread was interrupted before either the time period elapsed or the pool terminated successfully
*/
public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException {
Assert.checkMinimumParameter("timeout", 0, timeout);
Assert.checkNotNullParam("unit", unit);
if (timeout > 0) {
final Thread thread = Thread.currentThread();
if (runningThreads.contains(thread) || thread == schedulerThread) {
throw Messages.msg.cannotAwaitWithin();
}
Waiter waiters = this.terminationWaiters;
if (waiters == TERMINATE_COMPLETE_WAITER) {
return true;
}
final Waiter waiter = new Waiter(waiters);
waiter.setThread(currentThread());
while (! compareAndSetTerminationWaiters(waiters, waiter)) {
waiters = this.terminationWaiters;
if (waiters == TERMINATE_COMPLETE_WAITER) {
return true;
}
waiter.setNext(waiters);
}
try {
parkNanos(this, unit.toNanos(timeout));
} finally {
// prevent future spurious unparks without sabotaging the queue's integrity
waiter.setThread(null);
}
}
if (Thread.interrupted()) throw new InterruptedException();
return isTerminated();
}
// =======================================================
// ScheduledExecutorService
// =======================================================
public ScheduledFuture<?> schedule(final Runnable command, final long delay, final TimeUnit unit) {
startScheduleThread();
return schedulerTask.schedule(new RunnableScheduledFuture(command, delay, unit));
}
public <V> ScheduledFuture<V> schedule(final Callable<V> callable, final long delay, final TimeUnit unit) {
startScheduleThread();
return schedulerTask.schedule(new CallableScheduledFuture<V>(callable, delay, unit));
}
public ScheduledFuture<?> scheduleAtFixedRate(final Runnable command, final long initialDelay, final long period, final TimeUnit unit) {
startScheduleThread();
return schedulerTask.schedule(new FixedRateRunnableScheduledFuture(command, initialDelay, period, unit));
}
public ScheduledFuture<?> scheduleWithFixedDelay(final Runnable command, final long initialDelay, final long delay, final TimeUnit unit) {
startScheduleThread();
return schedulerTask.schedule(new FixedDelayRunnableScheduledFuture(command, initialDelay, delay, unit));
}
private void startScheduleThread() {
// this should be fairly quick...
if (schedulerThread.getState() == Thread.State.NEW) try {
schedulerThread.start();
} catch (IllegalThreadStateException ignored) {
// make sure it's race-proof
}
}
// =======================================================
// Management
// =======================================================
public StandardThreadPoolMXBean getThreadPoolMXBean() {
return mxBean;
}
// =======================================================
// Other public API
// =======================================================
/**
* Initiate shutdown of this thread pool. After this method is called, no new tasks will be accepted. Once
* the last task is complete, the thread pool will be terminated and its
* {@linkplain Builder#setTerminationTask(Runnable) termination task}
* will be called. Calling this method more than once has no additional effect, unless all previous calls
* had the {@code interrupt} parameter set to {@code false} and the subsequent call sets it to {@code true}, in
* which case all threads in the pool will be interrupted.
*
* @param interrupt {@code true} to request that currently-running tasks be interrupted; {@code false} otherwise
*/
public void shutdown(boolean interrupt) {
long oldStatus, newStatus;
// state change sh1:
// threadStatus ← threadStatus | shutdown
// succeeds: -
// preconditions:
// none (thread status may be in any state)
// postconditions (succeed):
// (always) ShutdownRequested set in threadStatus
// (maybe) ShutdownInterrupted set in threadStatus (depends on parameter)
// (maybe) ShutdownComplete set in threadStatus (if currentSizeOf() == 0)
// (maybe) exit if no change
// postconditions (fail): -
// post-actions (fail):
// repeat state change until success or return
do {
oldStatus = threadStatus;
newStatus = withShutdownRequested(oldStatus);
if (interrupt) newStatus = withShutdownInterrupt(newStatus);
if (currentSizeOf(oldStatus) == 0) newStatus = withShutdownComplete(newStatus);
if (newStatus == oldStatus) return;
} while (! compareAndSetThreadStatus(oldStatus, newStatus));
assert oldStatus != newStatus;
if (isShutdownRequested(newStatus) != isShutdownRequested(oldStatus)) {
assert ! isShutdownRequested(oldStatus); // because it can only ever be set, not cleared
// we initiated shutdown
// terminate the scheduler
schedulerTask.shutdown();
// clear out all consumers and append a dummy waiter node
TaskNode tail = this.tail;
QNode tailNext;
// a marker to indicate that termination was requested
for (;;) {
tailNext = tail.getNext();