-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathStealingScheduledThreadPool.java
More file actions
1159 lines (955 loc) · 42.4 KB
/
StealingScheduledThreadPool.java
File metadata and controls
1159 lines (955 loc) · 42.4 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
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 ca.spottedleaf.concurrentutil.scheduler;
import ca.spottedleaf.concurrentutil.list.COWArrayList;
import ca.spottedleaf.concurrentutil.numa.OSNuma;
import ca.spottedleaf.concurrentutil.util.ConcurrentUtil;
import ca.spottedleaf.concurrentutil.util.LazyRunnable;
import ca.spottedleaf.concurrentutil.util.TimeUtil;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
import java.lang.invoke.VarHandle;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.LockSupport;
import java.util.function.BooleanSupplier;
public final class StealingScheduledThreadPool extends Scheduler {
/**
* Schedules new tasks to the threads which are loaded the least.
*/
public static final long FLAG_SCHEDULE_EVENLY = 1L << 0;
/**
* Schedules new tasks to the nearest threads for the thread scheduling the task.
*/
public static final long FLAG_SCHEDULE_NEAR = 1L << 1;
public static final long DEFAULT_FLAGS = FLAG_SCHEDULE_EVENLY;
private final ThreadFactory threadFactory;
private final OSNuma numa;
private final COWArrayList<TickThreadRunner> coreThreads = new COWArrayList<>(TickThreadRunner.class);
private final COWArrayList<TickThreadRunner> aliveThreads = new COWArrayList<>(TickThreadRunner.class);
private final COWArrayList<NodeThreads> nodes = new COWArrayList<>(NodeThreads.class);
// used when adjusting threads
private final ReferenceOpenHashSet<SchedulableTick> allTasks = new ReferenceOpenHashSet<>();
private boolean shutdown;
private long stealThresholdNS;
private long taskTimeSliceNS;
private long flags;
public StealingScheduledThreadPool(final ThreadFactory threadFactory, final OSNuma numa) {
this.threadFactory = threadFactory;
this.numa = numa;
if (threadFactory == null) {
throw new NullPointerException("Null thread factory");
}
this.setFlags(DEFAULT_FLAGS);
}
public OSNuma getNuma() {
return this.numa;
}
private static ScheduledState getState(final SchedulableTick tick) {
return (ScheduledState)tick.getState();
}
private static Thread[] getThreads(final COWArrayList<TickThreadRunner> runners) {
final TickThreadRunner[] array = runners.getArray();
final Thread[] ret = new Thread[array.length];
for (int i = 0; i < array.length; ++i) {
ret[i] = array[i].thread;
}
return ret;
}
@Override
public Thread[] getAliveThreads() {
return getThreads(this.aliveThreads);
}
@Override
public Thread[] getCoreThreads() {
return getThreads(this.coreThreads);
}
public synchronized boolean isShutdown() {
return this.shutdown;
}
public synchronized boolean setThreadAllocation(final Int2IntMap threadsPerNode, final long stealThresholdNS,
final long taskTimeSliceNS) {
if (this.shutdown) {
return false;
}
this.stealThresholdNS = stealThresholdNS;
this.taskTimeSliceNS = taskTimeSliceNS;
final NodeThreads[] nodes = new NodeThreads[threadsPerNode.size()];
final List<TickThreadRunner> newRunners = new ArrayList<>();
int nodesIndex = 0;
for (final Int2IntMap.Entry entry : threadsPerNode.int2IntEntrySet()) {
final int node = entry.getIntKey();
final int threads = entry.getIntValue();
final TickThreadRunner[] runners = new TickThreadRunner[threads];
final NodeThreads nodeThreads = new NodeThreads(runners, node);
for (int i = 0; i < threads; ++i) {
final LazyRunnable run = new LazyRunnable();
run.setRunnable(runners[i] = new TickThreadRunner(this.threadFactory.newThread(run), this, nodeThreads, nodes));
newRunners.add(runners[i]);
this.aliveThreads.add(runners[i]);
}
nodes[nodesIndex++] = nodeThreads;
}
// swap the threads
final LongOpenHashSet oldRunners = new LongOpenHashSet(this.coreThreads.getArray().length);
for (final TickThreadRunner oldRunner : this.coreThreads.getArray()) {
oldRunners.add(oldRunner.id);
oldRunner.halt();
}
this.coreThreads.set(newRunners.toArray(new TickThreadRunner[0]));
this.nodes.set(nodes);
final SchedulableTick[] allTasks;
synchronized (this.allTasks) {
allTasks = this.allTasks.toArray(new SchedulableTick[0]);
}
for (final SchedulableTick tick : allTasks) {
final ScheduledState state = getState(tick);
final TickThreadRunner runner = state.getOwnedBy();
if (runner == null || oldRunners.contains(runner.id)) {
final TickThreadRunner newRunner = this.selectRunner(runner, this.nodes.getArray());
if (newRunner == runner) {
// both should be null
if (runner != null) {
throw new IllegalStateException();
}
continue;
}
state.transferScheduling(runner, newRunner);
}
}
// start new threads
if (this.numa.isAvailable()) {
final long[] prevAffinity = this.numa.getCurrentThreadAffinity();
try {
for (final NodeThreads node : this.nodes.getArray()) {
this.numa.setCurrentNumaAffinity(new int[] { node.nodeNumber });
for (final TickThreadRunner runner : node.threads) {
runner.thread.start();
}
}
} finally {
this.numa.setCurrentThreadAffinity(prevAffinity);
}
} else {
for (final TickThreadRunner runner : this.coreThreads.getArray()) {
runner.thread.start();
}
}
return true;
}
public synchronized boolean setFlags(final long flags) {
if (this.shutdown) {
return false;
}
this.flags = flags;
return true;
}
private void die(final TickThreadRunner runner) {
synchronized (this) {
this.aliveThreads.remove(runner);
}
}
@Override
public void halt() {
synchronized (this) {
this.shutdown = true;
}
for (final TickThreadRunner runner : this.coreThreads.getArray()) {
runner.halt();
}
}
@Override
public boolean join(final long msToWait) {
try {
return this.join(msToWait, false);
} catch (final InterruptedException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public boolean joinInterruptable(final long msToWait) throws InterruptedException {
return this.join(msToWait, true);
}
private boolean join(final long msToWait, final boolean interruptable) throws InterruptedException {
synchronized (this) {
if (!this.shutdown) {
throw new IllegalStateException("Attempting to join on non-shutdown pool");
}
}
final long nsToWait = TimeUnit.MILLISECONDS.toNanos(msToWait);
final long start = System.nanoTime();
final long deadline = start + nsToWait;
boolean interrupted = false;
try {
for (final TickThreadRunner runner : this.aliveThreads.getArray()) {
final Thread thread = runner.thread;
while (thread.isAlive()) {
try {
if (msToWait > 0L) {
final long current = System.nanoTime();
if (current - deadline >= 0L) {
return false;
}
thread.join(Duration.ofNanos(deadline - current));
} else {
thread.join();
}
} catch (final InterruptedException ex) {
if (interruptable) {
throw ex;
}
interrupted = true;
}
}
}
return true;
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
private TickThreadRunner selectRunner(final TickThreadRunner previousRunner, final NodeThreads[] nodes) {
final int currentNode = previousRunner == null ? this.numa.getCurrentNumaNode() : previousRunner.node.nodeNumber;
if ((this.flags & FLAG_SCHEDULE_NEAR) != 0L) {
TickThreadRunner selected = null;
int selectedDistance = Integer.MAX_VALUE;
int selectedSize = Integer.MAX_VALUE;
for (final NodeThreads node : nodes) {
final int rawDistance = this.numa.getNumaDistance(currentNode, node.nodeNumber);
final int distance = rawDistance <= 0 ? Integer.MAX_VALUE : rawDistance;
if (distance > selectedDistance) {
continue;
}
for (final TickThreadRunner runner : node.threads) {
// yes the size is just a rough guess...
final int size = runner.tickQueue.size();
// break ties on distance with size
if (distance < selectedDistance || size < selectedSize) {
// note: distance <= selectedDistance here
selected = runner;
selectedDistance = distance;
selectedSize = size;
}
}
}
return selected;
} else {
TickThreadRunner selected = null;
int selectedSize = Integer.MAX_VALUE;
int selectedDistance = Integer.MAX_VALUE;
for (final NodeThreads node : nodes) {
final int rawDistance = this.numa.getNumaDistance(currentNode, node.nodeNumber);
final int distance = rawDistance <= 0 ? Integer.MAX_VALUE : rawDistance;
for (final TickThreadRunner runner : node.threads) {
// yes the size is just a rough guess...
final int size = runner.tickQueue.size();
// break ties on size with numa distance
if (size < selectedSize || (size == selectedSize && distance < selectedDistance)) {
selected = runner;
selectedSize = size;
selectedDistance = distance;
}
}
}
return selected;
}
}
@Override
public void schedule(final SchedulableTick tick) {
NodeThreads[] nodes = this.nodes.getArray();
final ScheduledState state = new ScheduledState(tick);
if (!tick.setState(state)) {
throw new IllegalStateException("Task is already scheduled");
}
final TickThreadRunner initialRunner = this.selectRunner(null, nodes);
if (!state.initScheduling(this, initialRunner)) {
throw new IllegalStateException("Task is already scheduled");
}
// note: the task is now in the task set
// it may be possible that the runner we selected was halted while scheduling
// we can check for this by seeing if the nodes array changed
if (nodes != (nodes = this.nodes.getArray())) {
// try to re-assign the runner
// we do not need to repeat this if it fails, as the task is in the task set and would be
// handled by any future thread allocation change directly
state.transferScheduling(initialRunner, this.selectRunner(null, nodes));
}
// intermediate tasks are not handled during scheduling init
if (tick.hasTasks()) {
this.notifyTasks(tick);
}
}
@Override
public void notifyTasks(final SchedulableTick tick) {
if (tick.getState() instanceof ScheduledState state) {
state.scheduleTasks();
}
}
@Override
public boolean cancel(final SchedulableTick tick) {
if (tick.getState() instanceof ScheduledState state) {
return state.tryCancel();
} else {
return false;
}
}
// note: holds the tick's scheduled lock
private void tickAdded(final ScheduledState tick) {
synchronized (this.allTasks) {
this.allTasks.add(tick.tick);
}
}
// note: holds the tick's scheduled lock
private void tickCancelled(final ScheduledState tick) {
synchronized (this.allTasks) {
this.allTasks.remove(tick.tick);
}
}
private static final class ScheduledState {
private final SchedulableTick tick;
private StealingScheduledThreadPool scheduledTo;
private TickThreadRunner ownedBy;
private TickScheduleHolder tickScheduleHolder;
private TaskScheduleHolder taskScheduleHolder;
private static final int STATE_UNSCHEDULED = 1 << 0;
// scheduled but no intermediate tasks
private static final int STATE_IDLE = 1 << 1;
// scheduled but has intermediate tasks
private static final int STATE_HAS_TASKS = 1 << 2;
// running intermediate tasks or tick
private static final int STATE_RUNNING = 1 << 3;
private static final int STATE_RUNNING_CANCELLED = 1 << 4;
private static final int STATE_CANCELLED = 1 << 5;
private volatile int state = STATE_UNSCHEDULED;
private ScheduledState(final SchedulableTick tick) {
this.tick = tick;
}
private TickThreadRunner getOwnedBy() {
synchronized (this) {
return this.ownedBy;
}
}
private boolean initScheduling(final StealingScheduledThreadPool threadPool, final TickThreadRunner runner) {
synchronized (this) {
if (this.state != STATE_UNSCHEDULED) {
return false;
}
final long scheduledStart = this.tick.scheduledStart;
if (scheduledStart == TimeUtil.DEADLINE_NOT_SET) {
throw new IllegalStateException("Start must be set when scheduling");
}
threadPool.tickAdded(this);
this.scheduledTo = threadPool;
if (runner != null) {
this.ownedBy = runner;
this.tickScheduleHolder = new TickScheduleHolder(this, scheduledStart, false);
runner.tickQueue.put(this.tickScheduleHolder, Boolean.TRUE);
if (runner.findFirstTick() == this.tickScheduleHolder) {
runner.interruptIfIdle();
}
}
this.state = STATE_IDLE;
return true;
}
}
private boolean transferScheduling(final TickThreadRunner from, final TickThreadRunner to) {
synchronized (this) {
if (this.ownedBy != from) {
return false;
}
switch (this.state) {
case STATE_UNSCHEDULED: {
throw new IllegalStateException();
}
case STATE_IDLE: {
this.ownedBy = to;
// we need to re-schedule the tick task
this.reschedule(false);
if (this.taskScheduleHolder != null) {
throw new IllegalStateException();
}
return true;
}
case STATE_HAS_TASKS: {
this.ownedBy = to;
// we need to re-schedule the tick task
this.reschedule(false);
// re-schedule intermediate task if applicable
if (to == null) {
this.taskScheduleHolder = null;
} else {
if (this.taskScheduleHolder != null) {
this.taskScheduleHolder = new TaskScheduleHolder(this, this.taskScheduleHolder.lastDrainedTasks);
to.taskQueue.put(this.taskScheduleHolder, Boolean.TRUE);
to.interruptIfIdle();
}
}
return true;
}
case STATE_RUNNING: {
this.ownedBy = to;
// these will re-schedule these after the previous owner is done
this.tickScheduleHolder = null;
this.taskScheduleHolder = null;
return true;
}
case STATE_RUNNING_CANCELLED:
case STATE_CANCELLED: {
return false;
}
default: {
throw new IllegalStateException("Unknown state: " + this.state);
}
}
}
}
private boolean trySteal(final TickThreadRunner from, final TickThreadRunner to) {
synchronized (this) {
if (this.ownedBy != from) {
return false;
}
// can only steal tasks idling or awaiting task execution
switch (this.state) {
case STATE_UNSCHEDULED: {
throw new IllegalStateException();
}
case STATE_IDLE: {
this.ownedBy = to;
// we need to re-schedule the tick task
this.reschedule(true);
if (this.taskScheduleHolder != null) {
throw new IllegalStateException();
}
return true;
}
case STATE_HAS_TASKS: {
this.ownedBy = to;
// we need to re-schedule the tick task
this.reschedule(true);
// re-schedule intermediate task if applicable
if (to == null) {
this.taskScheduleHolder = null;
} else {
if (this.taskScheduleHolder != null) {
this.taskScheduleHolder = new TaskScheduleHolder(this, this.taskScheduleHolder.lastDrainedTasks);
to.taskQueue.put(this.taskScheduleHolder, Boolean.TRUE);
to.interruptIfIdle();
}
}
return true;
}
case STATE_RUNNING:
case STATE_RUNNING_CANCELLED:
case STATE_CANCELLED: {
return false;
}
default: {
throw new IllegalStateException("Unknown state: " + this.state);
}
}
}
}
private void scheduleTasks() {
final int currState = this.state;
if (currState != STATE_IDLE) {
// try to avoid acquiring lock unless we need to
// unscheduled, has tasks, is running, or is cancelled
return;
}
final long now = System.nanoTime();
synchronized (this) {
if (this.state != STATE_IDLE) {
return;
}
this.taskScheduleHolder = new TaskScheduleHolder(this, now);
if (this.ownedBy != null) {
this.ownedBy.taskQueue.put(this.taskScheduleHolder, Boolean.TRUE);
if (Thread.currentThread() != this.ownedBy.thread) {
this.ownedBy.interruptIfIdle();
}
}
this.state = STATE_HAS_TASKS;
}
}
// holds schedule lock
private void reschedule(final boolean stolen) {
final long scheduledStart = this.tick.scheduledStart;
if (scheduledStart == TimeUtil.DEADLINE_NOT_SET) {
throw new IllegalStateException("Start must be set when scheduling");
}
if (this.ownedBy != null) {
this.tickScheduleHolder = new TickScheduleHolder(this, scheduledStart, stolen);
this.ownedBy.tickQueue.put(this.tickScheduleHolder, Boolean.TRUE);
if (Thread.currentThread() != this.ownedBy.thread && this.ownedBy.findFirstTick() == this.tickScheduleHolder) {
this.ownedBy.tryInterrupt();
}
}
}
private boolean trySetRunning(final TickThreadRunner expectedOwner) {
synchronized (this) {
if (this.ownedBy != expectedOwner) {
return false;
}
switch (this.state) {
case STATE_UNSCHEDULED: {
throw new IllegalStateException("Cannot be unscheduled here");
}
case STATE_IDLE:
case STATE_HAS_TASKS: {
this.state = STATE_RUNNING;
return true;
}
case STATE_RUNNING:
case STATE_RUNNING_CANCELLED:
case STATE_CANCELLED: {
return false;
}
default: {
throw new IllegalStateException("Unknown state: " + this.state);
}
}
}
}
private boolean tryCancel() {
synchronized (this) {
switch (this.state) {
case STATE_UNSCHEDULED: {
return false;
}
case STATE_IDLE:
case STATE_HAS_TASKS: {
this.doCancel();
return true;
}
case STATE_RUNNING: {
this.state = STATE_RUNNING_CANCELLED;
return true;
}
case STATE_RUNNING_CANCELLED:
case STATE_CANCELLED: {
return false;
}
default: {
throw new IllegalStateException("Unknown state: " + this.state);
}
}
}
}
// only run if trySetRunning() returns true
private void finishTaskExecution(final boolean cancel) {
synchronized (this) {
if (this.state != STATE_RUNNING && this.state != STATE_RUNNING_CANCELLED) {
throw new IllegalStateException("Must be running here");
}
if (cancel || this.state == STATE_RUNNING_CANCELLED) {
this.doCancel();
return;
} else {
this.taskScheduleHolder = null;
if (this.tickScheduleHolder == null) {
// this task was stolen while running tasks, and as a result was not scheduled to its new thread
this.reschedule(false);
}
this.state = STATE_IDLE;
// note: expect caller to invoke notifyTasks if there are still more tasks
}
}
}
// holds schedule lock
private void doCancel() {
if (this.tickScheduleHolder != null) {
if (this.ownedBy != null) {
this.ownedBy.tickQueue.remove(this.tickScheduleHolder);
}
this.tickScheduleHolder = null;
}
if (this.taskScheduleHolder != null) {
if (this.ownedBy != null) {
this.ownedBy.taskQueue.remove(this.taskScheduleHolder);
}
this.taskScheduleHolder = null;
}
this.state = STATE_CANCELLED;
this.scheduledTo.tickCancelled(this);
}
private void finishTickExecution(final boolean cancel) {
synchronized (this) {
if (this.state != STATE_RUNNING && this.state != STATE_RUNNING_CANCELLED) {
throw new IllegalStateException("Must be running here");
}
if (cancel || this.state == STATE_RUNNING_CANCELLED) {
this.doCancel();
return;
} else {
// be fair to other tasks, reset the task holder
// we expect the caller to invoke notifyTasks if needed
// (this also simplifies the logic here to determine the new state)
if (this.taskScheduleHolder != null) {
if (this.ownedBy != null) {
this.ownedBy.taskQueue.remove(this.taskScheduleHolder);
}
this.taskScheduleHolder = null;
}
// old tick holder is either null or taken, we must re-schedule
this.tickScheduleHolder = null;
this.reschedule(false);
this.state = STATE_IDLE;
}
}
}
}
private static final class NodeThreads {
private final TickThreadRunner[] threads;
private final int nodeNumber;
private NodeThreads(final TickThreadRunner[] threads, final int nodeNumber) {
this.threads = threads;
this.nodeNumber = nodeNumber;
}
}
private static final class TickScheduleHolder {
private static final AtomicLong ID_GENERATOR = new AtomicLong();
private final long id = ID_GENERATOR.getAndIncrement();
private static final Comparator<TickScheduleHolder> COMPARATOR = (final TickScheduleHolder h1, final TickScheduleHolder h2) -> {
final int timeCompare = TimeUtil.compareTimes(h1.atNS, h2.atNS);
if (timeCompare != 0) {
return timeCompare;
}
return Long.compare(h1.id, h2.id);
};
private final ScheduledState tick;
private final long atNS;
private final boolean stolen;
private TickScheduleHolder(final ScheduledState tick, final long atNS, final boolean stolen) {
this.tick = tick;
this.atNS = atNS;
this.stolen = stolen;
}
}
private static final class TaskScheduleHolder {
private static final AtomicLong ID_GENERATOR = new AtomicLong();
private final long id = ID_GENERATOR.getAndIncrement();
private static final Comparator<TaskScheduleHolder> COMPARATOR = (final TaskScheduleHolder h1, final TaskScheduleHolder h2) -> {
// want older timestamps first
final int timeCompare = TimeUtil.compareTimes(h2.lastDrainedTasks, h1.lastDrainedTasks);
if (timeCompare != 0) {
return timeCompare;
}
return Long.compare(h1.id, h2.id);
};
private final ScheduledState task;
private final long lastDrainedTasks;
private TaskScheduleHolder(final ScheduledState task, final long lastDrainedTasks) {
this.task = task;
this.lastDrainedTasks = lastDrainedTasks;
}
}
private static final class TickThreadRunner implements Runnable {
private static final AtomicLong ID_GENERATOR = new AtomicLong();
private final long id = ID_GENERATOR.getAndIncrement();
// we force idle threads to wake up periodically so that they can steal tasks
private static final long MAX_IDLE_TIME = TimeUnit.MILLISECONDS.toNanos(10L);
private final Thread thread;
private final StealingScheduledThreadPool scheduler;
private final NodeThreads node;
private final NodeThreads[] nodes;
private static final int STATE_NOT_STARTED = 1 << 0;
private static final int STATE_IDLE = 1 << 1;
private static final int STATE_INTERRUPTED = 1 << 2;
private static final int STATE_EXECUTING_TASKS = 1 << 3;
private static final int STATE_EXECUTING_TICK = 1 << 4;
private static final int STATE_HALTED = 1 << 5;
private volatile int state = STATE_NOT_STARTED;
private static final VarHandle STATE_HANDLE = ConcurrentUtil.getVarHandle(TickThreadRunner.class, "state", int.class);
private final ConcurrentSkipListMap<TickScheduleHolder, Boolean> tickQueue = new ConcurrentSkipListMap<>(TickScheduleHolder.COMPARATOR);
private final ConcurrentSkipListMap<TaskScheduleHolder, Boolean> taskQueue = new ConcurrentSkipListMap<>(TaskScheduleHolder.COMPARATOR);
private int getStateVolatile() {
return (int)STATE_HANDLE.getVolatile(this);
}
private void setStateVolatile(final int value) {
STATE_HANDLE.setVolatile(this, value);
}
private int exchangeStateVolatile(final int value) {
return (int)STATE_HANDLE.getAndSet(this, value);
}
private int compareAndExchangeStateVolatile(final int expect, final int update) {
return (int)STATE_HANDLE.compareAndExchange(this, expect, update);
}
private TickThreadRunner(final Thread thread, final StealingScheduledThreadPool scheduler, final NodeThreads node,
final NodeThreads[] nodes) {
this.thread = thread;
this.scheduler = scheduler;
this.node = node;
this.nodes = nodes;
}
private void interruptIfIdle() {
final int state = this.getStateVolatile();
if (state == STATE_IDLE) {
if (state == this.compareAndExchangeStateVolatile(state, STATE_INTERRUPTED)) {
LockSupport.unpark(this.thread);
} // else: not idle
} // else: not idle
}
private void halt() {
if (STATE_IDLE == this.exchangeStateVolatile(STATE_HALTED)) {
LockSupport.unpark(this.thread);
}
}
private void tryInterrupt() {
for (int state = this.getStateVolatile(), failures = 0;;) {
for (int i = 0; i < failures; ++i) {
ConcurrentUtil.backoff();
}
++failures;
switch (state) {
case STATE_IDLE: {
if (state == (state = this.compareAndExchangeStateVolatile(state, STATE_INTERRUPTED))) {
// need to unpark if idle
LockSupport.unpark(this.thread);
return;
}
break;
}
case STATE_EXECUTING_TASKS: {
if (state == (state = this.compareAndExchangeStateVolatile(state, STATE_INTERRUPTED))) {
return;
}
break;
}
case STATE_NOT_STARTED:
case STATE_INTERRUPTED:
case STATE_EXECUTING_TICK:
case STATE_HALTED: {
return;
}
default: {
throw new IllegalStateException("Unknown state: " + state);
}
}
}
}
private TickScheduleHolder findFirstTick() {
final Map.Entry<TickScheduleHolder, Boolean> first = this.tickQueue.firstEntry();
return first == null ? null : first.getKey();
}
private TaskScheduleHolder findFirstTask() {
final Map.Entry<TaskScheduleHolder, Boolean> first = this.taskQueue.firstEntry();
return first == null ? null : first.getKey();
}
private void tryStealTask() {
final TickScheduleHolder ourDeadlineHolder = this.findFirstTick();
final long ourEarliest = ourDeadlineHolder == null ? TimeUtil.DEADLINE_NOT_SET : ourDeadlineHolder.atNS;
final long now = System.nanoTime();
final long stealThreshold = this.scheduler.stealThresholdNS;
// find any task behind by the steal delay
ScheduledState selected = null;
// we adjust by the numa distance so that we can try to avoid shuffling tasks around nodes unless needed
long selectedBehindAdjusted = Long.MIN_VALUE;
int selectedDistance = Integer.MAX_VALUE;
TickThreadRunner selectedRunner = null;
for (final NodeThreads node : this.nodes) {
final int rawDistance = this.scheduler.numa.getNumaDistance(this.node.nodeNumber, node.nodeNumber);
final int distance = rawDistance <= 0 ? Integer.MAX_VALUE : rawDistance;
for (final TickThreadRunner runner : node.threads) {
if (runner == this) {
// can't steal from ourselves
continue;
}
final TickScheduleHolder holder = runner.findFirstTick();
if (holder == null) {
// nothing to steal
continue;
}
if (holder.stolen) {
// already stolen
continue;
}
final long holderStart = holder.atNS;
if (ourEarliest != TimeUtil.DEADLINE_NOT_SET && TimeUtil.compareTimes(holderStart, ourEarliest) >= 0L) {
// this task is later than ours
continue;
}
final long behindBy = now - holderStart;
if (behindBy < stealThreshold) {
// below the steal threshold
continue;
}
// adjust the behind so that we prefer to steal tasks on closer nodes
// (tasks on closer nodes appear to be behind by more than tasks on farther nodes)
final long behindAdjusted = behindBy / distance;
if (behindAdjusted > selectedBehindAdjusted || (behindAdjusted == selectedBehindAdjusted && distance < selectedDistance)) {
selected = holder.tick;
selectedBehindAdjusted = behindAdjusted;
selectedDistance = distance;
selectedRunner = runner;
}
}
}
if (selected != null) {
// try to steal
if (selected.trySteal(selectedRunner, this)) {
this.tryInterrupt();
}
}
}
private void begin() {
// set numa
if (this.scheduler.numa.isAvailable()) {
this.scheduler.numa.setCurrentNumaAffinity(new int[]{ this.node.nodeNumber });
}
// use CAS in case we are halted already
this.compareAndExchangeStateVolatile(STATE_NOT_STARTED, STATE_INTERRUPTED);
}
private void doRun() {
while (this.mainLoop());
}
// returns true if deadline was reached, false if interrupted or halted
private boolean executeTasksUntil(final long deadline) {
final long timeSlice = this.scheduler.taskTimeSliceNS;
for (;;) {
// stealing a task here will set state to interrupted
this.tryStealTask();
// expect state idle here
final TaskScheduleHolder taskHolder = this.findFirstTask();
if (taskHolder == null) {
// no tasks, go to idle
while (this.getStateVolatile() == STATE_IDLE) {
Thread.interrupted();