-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathEDFSchedulerThreadPool.java
More file actions
553 lines (464 loc) · 19.1 KB
/
EDFSchedulerThreadPool.java
File metadata and controls
553 lines (464 loc) · 19.1 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
package ca.spottedleaf.concurrentutil.scheduler;
import ca.spottedleaf.concurrentutil.set.LinkedSortedSet;
import ca.spottedleaf.concurrentutil.util.ConcurrentUtil;
import ca.spottedleaf.concurrentutil.util.LazyRunnable;
import ca.spottedleaf.concurrentutil.util.TimeUtil;
import java.lang.invoke.VarHandle;
import java.time.Duration;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
/**
* Scheduler thread pool implementation that uses EDF scheduling.
* <p>
* Intermediate task execution is not supported in this scheduler.
* </p>
* <p>
* NUMA aware scheduling is not supported in this scheduler.
* </p>
*/
public final class EDFSchedulerThreadPool extends Scheduler {
private static final Comparator<ScheduledState> TICK_COMPARATOR_BY_TIME = (final ScheduledState s1, final ScheduledState s2) -> {
final SchedulableTick t1 = s1.tick;
final SchedulableTick t2 = s2.tick;
final int timeCompare = TimeUtil.compareTimes(t1.scheduledStart, t2.scheduledStart);
if (timeCompare != 0) {
return timeCompare;
}
return Long.signum(t1.id - t2.id);
};
private final TickThreadRunner[] runners;
private final Thread[] threads;
private final LinkedSortedSet<ScheduledState> awaiting = new LinkedSortedSet<>(TICK_COMPARATOR_BY_TIME);
private final PriorityQueue<ScheduledState> queued = new PriorityQueue<>(TICK_COMPARATOR_BY_TIME);
private final BitSet idleThreads;
private final Object scheduleLock = new Object();
private volatile boolean halted;
/**
* Creates, but does not start, a scheduler thread pool with the specified number of threads
* created using the specified thread factory.
* @param threads Specified number of threads
* @param threadFactory Specified thread factory
* @see #start()
*/
public EDFSchedulerThreadPool(final int threads, final ThreadFactory threadFactory) {
final BitSet idleThreads = new BitSet(threads);
for (int i = 0; i < threads; ++i) {
idleThreads.set(i);
}
this.idleThreads = idleThreads;
final TickThreadRunner[] runners = new TickThreadRunner[threads];
final Thread[] t = new Thread[threads];
for (int i = 0; i < threads; ++i) {
final LazyRunnable run = new LazyRunnable();
final Thread thread = t[i] = threadFactory.newThread(run);
run.setRunnable(runners[i] = new TickThreadRunner(thread, i, this));
}
this.threads = t;
this.runners = runners;
}
/**
* Starts the threads in this pool.
*/
public void start() {
for (final Thread thread : this.threads) {
thread.start();
}
}
@Override
public void halt() {
this.halted = true;
for (final Thread thread : this.threads) {
// force response to halt
LockSupport.unpark(thread);
}
}
@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 {
final long nsToWait = TimeUnit.MILLISECONDS.toNanos(msToWait);
final long start = System.nanoTime();
final long deadline = start + nsToWait;
boolean interrupted = false;
try {
for (final Thread thread : this.threads) {
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();
}
}
}
/**
* Returns an array of the underlying scheduling threads.
*/
public Thread[] getThreads() {
return this.threads.clone();
}
@Override
public Thread[] getCoreThreads() {
return this.getThreads();
}
@Override
public Thread[] getAliveThreads() {
final List<Thread> ret = new ArrayList<>(this.threads.length);
for (final Thread thread : this.threads) {
if (thread.isAlive()) {
ret.add(thread);
}
}
return ret.toArray(new Thread[0]);
}
private void insertFresh(final ScheduledState task) {
final TickThreadRunner[] runners = this.runners;
final int firstIdleThread = this.idleThreads.nextSetBit(0);
if (firstIdleThread != -1) {
// push to idle thread
this.idleThreads.clear(firstIdleThread);
final TickThreadRunner runner = runners[firstIdleThread];
task.awaitingLink = this.awaiting.addLast(task);
runner.acceptTask(task);
return;
}
// try to replace the last awaiting task
final ScheduledState last = this.awaiting.last();
if (last != null && TICK_COMPARATOR_BY_TIME.compare(task, last) < 0) {
// need to replace the last task
this.awaiting.pollLast();
last.awaitingLink = null;
task.awaitingLink = this.awaiting.addLast(task);
// need to add task to queue to be picked up later
this.queued.add(last);
final TickThreadRunner runner = last.ownedBy;
runner.replaceTask(task);
return;
}
// add to queue, will be picked up later
this.queued.add(task);
}
private void takeTask(final TickThreadRunner runner, final ScheduledState tick) {
if (!this.awaiting.remove(tick.awaitingLink)) {
throw new IllegalStateException("Task is not in awaiting");
}
tick.awaitingLink = null;
}
private ScheduledState returnTask(final TickThreadRunner runner, final ScheduledState reschedule) {
if (reschedule != null) {
this.queued.add(reschedule);
}
final ScheduledState ret = this.queued.poll();
if (ret == null) {
this.idleThreads.set(runner.id);
} else {
ret.awaitingLink = this.awaiting.addLast(ret);
}
return ret;
}
@Override
public void schedule(final SchedulableTick task) {
synchronized (this.scheduleLock) {
if (task.getScheduledStart() == TimeUtil.DEADLINE_NOT_SET) {
throw new IllegalStateException("Start must be set when scheduling");
}
final ScheduledState state = new ScheduledState(task);
if (!task.setState(state)) {
throw new IllegalStateException("Task " + task + " is already scheduled or cancelled");
}
if (!state.tryMarkScheduled()) {
throw new IllegalStateException();
}
state.schedulerOwnedBy = this;
this.insertFresh(state);
}
}
/**
* Updates the tasks scheduled start to the maximum of its current scheduled start and the specified
* new start. If the task is not scheduled, returns {@code false}. Otherwise, returns whether the
* scheduled start was updated. Undefined behavior of the specified task is scheduled in another executor.
* @param task Specified task
* @param newStart Specified new start
*/
public boolean updateTickStartToMax(final ScheduledState task, final long newStart) {
synchronized (this.scheduleLock) {
if (TimeUtil.compareTimes(newStart, task.tick.getScheduledStart()) <= 0) {
return false;
}
if (this.queued.remove(task)) {
task.tick.setScheduledStart(newStart);
this.queued.add(task);
return true;
}
if (task.awaitingLink != null) {
this.awaiting.remove(task.awaitingLink);
task.awaitingLink = null;
// re-queue task
task.tick.setScheduledStart(newStart);
this.queued.add(task);
// now we need to replace the task the runner was waiting for
final TickThreadRunner runner = task.ownedBy;
final ScheduledState replace = this.queued.poll();
// replace cannot be null, since we have added a task to queued
if (replace != task) {
runner.replaceTask(replace);
}
return true;
}
return false;
}
}
@Override
public boolean cancel(final SchedulableTick task) {
if (!(task.getState() instanceof ScheduledState state)) {
return false;
}
synchronized (this.scheduleLock) {
if (state.schedulerOwnedBy != this) {
return false;
}
if (!state.tryMarkCancelled()) {
return false;
}
if (this.queued.remove(state)) {
// cancelled, and no runner owns it - so return
return true;
}
if (state.awaitingLink != null) {
this.awaiting.remove(state.awaitingLink);
state.awaitingLink = null;
// here we need to replace the task the runner was waiting for
final TickThreadRunner runner = state.ownedBy;
final ScheduledState replace = this.queued.poll();
if (replace == null) {
// nothing to replace with, set to idle
this.idleThreads.set(runner.id);
runner.forceIdle();
} else {
runner.replaceTask(replace);
}
return true;
}
// could not find it in queue
return false;
}
}
@Override
public void notifyTasks(final SchedulableTick task) {
// Not implemented
}
private static final class ScheduledState {
private final SchedulableTick tick;
private static final int SCHEDULE_STATE_NOT_SCHEDULED = 0;
private static final int SCHEDULE_STATE_SCHEDULED = 1;
private static final int SCHEDULE_STATE_CANCELLED = 2;
private final AtomicInteger scheduled = new AtomicInteger();
private EDFSchedulerThreadPool schedulerOwnedBy;
private TickThreadRunner ownedBy;
private LinkedSortedSet.Link<ScheduledState> awaitingLink;
private ScheduledState(final SchedulableTick tick) {
this.tick = tick;
}
private boolean tryMarkScheduled() {
return this.scheduled.compareAndSet(SCHEDULE_STATE_NOT_SCHEDULED, SCHEDULE_STATE_SCHEDULED);
}
private boolean tryMarkCancelled() {
return this.scheduled.compareAndSet(SCHEDULE_STATE_SCHEDULED, SCHEDULE_STATE_CANCELLED);
}
private boolean isScheduled() {
return this.scheduled.get() == SCHEDULE_STATE_SCHEDULED;
}
}
private static final class TickThreadRunner implements Runnable {
/**
* There are no tasks in this thread's runqueue, so it is parked.
* <p>
* stateTarget = null
* </p>
*/
private static final int STATE_IDLE = 0;
/**
* The runner is waiting to tick a task, as it has no intermediate tasks to execute.
* <p>
* stateTarget = the task awaiting tick
* </p>
*/
private static final int STATE_AWAITING_TICK = 1;
/**
* The runner is executing a tick for one of the tasks that was in its runqueue.
* <p>
* stateTarget = the task being ticked
* </p>
*/
private static final int STATE_EXECUTING_TICK = 2;
private final Thread thread;
public final int id;
public final EDFSchedulerThreadPool scheduler;
private volatile TickThreadRunnerState state = new TickThreadRunnerState(null, STATE_IDLE);
private static final VarHandle STATE_HANDLE = ConcurrentUtil.getVarHandle(TickThreadRunner.class, "state", TickThreadRunnerState.class);
private void setStatePlain(final TickThreadRunnerState state) {
STATE_HANDLE.set(this, state);
}
private void setStateOpaque(final TickThreadRunnerState state) {
STATE_HANDLE.setOpaque(this, state);
}
private void setStateVolatile(final TickThreadRunnerState state) {
STATE_HANDLE.setVolatile(this, state);
}
private static record TickThreadRunnerState(ScheduledState stateTarget, int state) {}
public TickThreadRunner(final Thread thread, final int id, final EDFSchedulerThreadPool scheduler) {
this.thread = thread;
this.id = id;
this.scheduler = scheduler;
}
private Thread getRunnerThread() {
return this.thread;
}
private void acceptTask(final ScheduledState task) {
if (task.ownedBy != null) {
throw new IllegalStateException("Already owned by another runner");
}
task.ownedBy = this;
final TickThreadRunnerState state = this.state;
if (state.state != STATE_IDLE) {
throw new IllegalStateException("Cannot accept task in state " + state);
}
this.setStateVolatile(new TickThreadRunnerState(task, STATE_AWAITING_TICK));
LockSupport.unpark(this.getRunnerThread());
}
private void replaceTask(final ScheduledState task) {
final TickThreadRunnerState state = this.state;
if (state.state != STATE_AWAITING_TICK) {
throw new IllegalStateException("Cannot replace task in state " + state);
}
if (task.ownedBy != null) {
throw new IllegalStateException("Already owned by another runner");
}
task.ownedBy = this;
state.stateTarget.ownedBy = null;
this.setStateVolatile(new TickThreadRunnerState(task, STATE_AWAITING_TICK));
LockSupport.unpark(this.getRunnerThread());
}
private void forceIdle() {
final TickThreadRunnerState state = this.state;
if (state.state != STATE_AWAITING_TICK) {
throw new IllegalStateException("Cannot replace task in state " + state);
}
state.stateTarget.ownedBy = null;
this.setStateOpaque(new TickThreadRunnerState(null, STATE_IDLE));
// no need to unpark
}
private boolean takeTask(final TickThreadRunnerState state, final ScheduledState task) {
synchronized (this.scheduler.scheduleLock) {
if (this.state != state) {
return false;
}
this.setStatePlain(new TickThreadRunnerState(task, STATE_EXECUTING_TICK));
this.scheduler.takeTask(this, task);
return true;
}
}
private void returnTask(final ScheduledState task, final boolean reschedule) {
synchronized (this.scheduler.scheduleLock) {
task.ownedBy = null;
final ScheduledState newWait = this.scheduler.returnTask(this, reschedule && task.isScheduled() ? task : null);
if (newWait == null) {
this.setStatePlain(new TickThreadRunnerState(null, STATE_IDLE));
} else {
if (newWait.ownedBy != null) {
throw new IllegalStateException("Already owned by another runner");
}
newWait.ownedBy = this;
this.setStatePlain(new TickThreadRunnerState(newWait, STATE_AWAITING_TICK));
}
}
}
@Override
public void run() {
main_state_loop:
for (;;) {
final TickThreadRunnerState startState = this.state;
final int startStateType = startState.state;
final ScheduledState startStateTask = startState.stateTarget;
if (this.scheduler.halted) {
return;
}
switch (startStateType) {
case STATE_IDLE: {
while (this.state.state == STATE_IDLE) {
Thread.interrupted();
LockSupport.park();
if (this.scheduler.halted) {
return;
}
}
continue main_state_loop;
}
case STATE_AWAITING_TICK: {
final long deadline = startStateTask.tick.getScheduledStart();
for (;;) {
if (this.state != startState) {
continue main_state_loop;
}
Thread.interrupted();
final long diff = deadline - System.nanoTime();
if (diff <= 0L) {
break;
}
LockSupport.parkNanos(startState, diff);
if (this.scheduler.halted) {
return;
}
}
if (!this.takeTask(startState, startStateTask)) {
continue main_state_loop;
}
// TODO exception handling
final boolean reschedule = startStateTask.tick.runTick();
this.returnTask(startStateTask, reschedule);
continue main_state_loop;
}
case STATE_EXECUTING_TICK: {
throw new IllegalStateException("Tick execution must be set by runner thread, not by any other thread");
}
default: {
throw new IllegalStateException("Unknown state: " + startState);
}
}
}
}
}
}