-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
Copy pathQueueDrainHelper.java
617 lines (534 loc) · 19.1 KB
/
QueueDrainHelper.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
/**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package io.reactivex.internal.util;
import java.util.Queue;
import java.util.concurrent.atomic.*;
import org.reactivestreams.*;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.BooleanSupplier;
import io.reactivex.internal.fuseable.SimpleQueue;
import io.reactivex.internal.queue.*;
/**
* Utility class to help with the queue-drain serialization idiom.
*/
public enum QueueDrainHelper {
;
/**
* A fast-path queue-drain serialization logic.
* <p>The decrementing of the state is left to the drain callback.
* @param <T> the instance type
* @param instance
* @param fastPath called if the instance is uncontended.
* @param queue called if the instance is contended to queue up work
* @param drain called if the instance transitions to the drain state successfully
*/
public static <T> void queueDrain(AtomicInteger instance,
Runnable fastPath, Runnable queue, Runnable drain) {
if (instance.get() == 0 && instance.compareAndSet(0, 1)) {
fastPath.run();
if (instance.decrementAndGet() == 0) {
return;
}
} else {
queue.run();
if (instance.getAndIncrement() != 0) {
return;
}
}
drain.run();
}
/**
* A fast-path queue-drain serialization logic with the ability to leave the state
* in fastpath/drain mode or not continue after the call to queue.
* <p>The decrementing of the state is left to the drain callback.
* @param <T> the instance type
* @param instance
* @param fastPath
* @param queue
* @param drain
* @throws Exception
*/
public static <T> void queueDrainIf(AtomicInteger instance,
BooleanSupplier fastPath, BooleanSupplier queue, Runnable drain) throws Exception {
if (instance.get() == 0 && instance.compareAndSet(0, 1)) {
if (fastPath.getAsBoolean()) {
return;
}
if (instance.decrementAndGet() == 0) {
return;
}
} else {
if (queue.getAsBoolean()) {
return;
}
if (instance.getAndIncrement() != 0) {
return;
}
}
drain.run();
}
/**
* A fast-path queue-drain serialization logic where the drain is looped until
* the instance state reaches 0 again.
* @param <T> the instance type
* @param instance
* @param fastPath
* @param queue
* @param drain
*/
public static <T> void queueDrainLoop(AtomicInteger instance,
Runnable fastPath, Runnable queue, Runnable drain) {
if (instance.get() == 0 && instance.compareAndSet(0, 1)) {
fastPath.run();
if (instance.decrementAndGet() == 0) {
return;
}
} else {
queue.run();
if (instance.getAndIncrement() != 0) {
return;
}
}
int missed = 1;
for (;;) {
drain.run();
missed = instance.addAndGet(-missed);
if (missed == 0) {
return;
}
}
}
/**
* A fast-path queue-drain serialization logic with looped drain call and the ability to leave the state
* in fastpath/drain mode or not continue after the call to queue.
* @param <T> the instance type
* @param instance
* @param fastPath
* @param queue
* @param drain
* @throws Exception
*/
public static <T> void queueDrainLoopIf(AtomicInteger instance,
BooleanSupplier fastPath, BooleanSupplier queue, BooleanSupplier drain) throws Exception {
if (instance.get() == 0 && instance.compareAndSet(0, 1)) {
if (fastPath.getAsBoolean()) {
return;
}
if (instance.decrementAndGet() == 0) {
return;
}
} else {
if (queue.getAsBoolean()) {
return;
}
if (instance.getAndIncrement() != 0) {
return;
}
}
int missed = 1;
for (;;) {
if (drain.getAsBoolean()) {
return;
}
missed = instance.addAndGet(-missed);
if (missed == 0) {
return;
}
}
}
public static <T, U> void drainLoop(SimpleQueue<T> q, Subscriber<? super U> a, boolean delayError, QueueDrain<T, U> qd) {
int missed = 1;
for (;;) {
if (checkTerminated(qd.done(), q.isEmpty(), a, delayError, q, qd)) {
return;
}
long r = qd.requested();
long e = 0L;
while (e != r) {
boolean d = qd.done();
T v;
try {
v = q.poll();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
a.onError(ex);
return;
}
boolean empty = v == null;
if (checkTerminated(d, empty, a, delayError, q, qd)) {
return;
}
if (empty) {
break;
}
if (qd.accept(a, v)) {
e++;
}
}
if (e != 0L && r != Long.MAX_VALUE) {
qd.produced(e);
}
missed = qd.leave(-missed);
if (missed == 0) {
break;
}
}
}
/**
* Drain the queue but give up with an error if there aren't enough requests.
* @param <T> the queue value type
* @param <U> the emission value type
* @param q the queue
* @param a the subscriber
* @param delayError true if errors should be delayed after all normal items
* @param dispose the disposable to call when termination happens and cleanup is necessary
* @param qd the QueueDrain instance that gives status information to the drain logic
*/
public static <T, U> void drainMaxLoop(SimpleQueue<T> q, Subscriber<? super U> a, boolean delayError,
Disposable dispose, QueueDrain<T, U> qd) {
int missed = 1;
for (;;) {
for (;;) {
boolean d = qd.done();
T v;
try {
v = q.poll();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
a.onError(ex);
return;
}
boolean empty = v == null;
if (checkTerminated(d, empty, a, delayError, q, qd)) {
if (dispose != null) {
dispose.dispose();
}
return;
}
if (empty) {
break;
}
long r = qd.requested();
if (r != 0L) {
if (qd.accept(a, v)) {
if (r != Long.MAX_VALUE) {
r = qd.produced(1);
}
}
} else {
q.clear();
if (dispose != null) {
dispose.dispose();
}
a.onError(new IllegalStateException("Could not emit value due to lack of requests."));
return;
}
}
missed = qd.leave(-missed);
if (missed == 0) {
break;
}
}
}
public static <T, U> boolean checkTerminated(boolean d, boolean empty,
Subscriber<?> s, boolean delayError, SimpleQueue<?> q, QueueDrain<T, U> qd) {
if (qd.cancelled()) {
q.clear();
return true;
}
if (d) {
if (delayError) {
if (empty) {
Throwable err = qd.error();
if (err != null) {
s.onError(err);
} else {
s.onComplete();
}
return true;
}
} else {
Throwable err = qd.error();
if (err != null) {
q.clear();
s.onError(err);
return true;
} else
if (empty) {
s.onComplete();
return true;
}
}
}
return false;
}
public static <T, U> void drainLoop(SimpleQueue<T> q, Observer<? super U> a, boolean delayError, Disposable dispose, NbpQueueDrain<T, U> qd) {
int missed = 1;
for (;;) {
if (checkTerminated(qd.done(), q.isEmpty(), a, delayError, q, dispose, qd)) {
return;
}
for (;;) {
boolean d = qd.done();
T v;
try {
v = q.poll();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
a.onError(ex);
return;
}
boolean empty = v == null;
if (checkTerminated(d, empty, a, delayError, q, dispose, qd)) {
return;
}
if (empty) {
break;
}
qd.accept(a, v);
}
missed = qd.leave(-missed);
if (missed == 0) {
break;
}
}
}
public static <T, U> boolean checkTerminated(boolean d, boolean empty,
Observer<?> s, boolean delayError, SimpleQueue<?> q, Disposable disposable, NbpQueueDrain<T, U> qd) {
if (qd.cancelled()) {
q.clear();
disposable.dispose();
return true;
}
if (d) {
if (delayError) {
if (empty) {
disposable.dispose();
Throwable err = qd.error();
if (err != null) {
s.onError(err);
} else {
s.onComplete();
}
return true;
}
} else {
Throwable err = qd.error();
if (err != null) {
q.clear();
disposable.dispose();
s.onError(err);
return true;
} else
if (empty) {
disposable.dispose();
s.onComplete();
return true;
}
}
}
return false;
}
/**
* Creates a queue: spsc-array if capacityHint is positive and
* spsc-linked-array if capacityHint is negative; in both cases, the
* capacity is the absolute value of prefetch.
* @param <T> the value type of the queue
* @param capacityHint the capacity hint
* @return the queue instance
*/
public static <T> SimpleQueue<T> createQueue(int capacityHint) {
if (capacityHint < 0) {
return new SpscLinkedArrayQueue<T>(-capacityHint);
}
return new SpscArrayQueue<T>(capacityHint);
}
/**
* Requests Long.MAX_VALUE if prefetch is negative or the exact
* amount if prefetch is positive.
* @param s the Subscription to request from
* @param prefetch the prefetch value
*/
public static void request(Subscription s, int prefetch) {
s.request(prefetch < 0 ? Long.MAX_VALUE : prefetch);
}
static final long COMPLETED_MASK = 0x8000000000000000L;
static final long REQUESTED_MASK = 0x7FFFFFFFFFFFFFFFL;
/**
* Accumulates requests (validated) and handles the completed mode draining of the queue based on the requests.
*
* <p>
* Post-completion backpressure handles the case when a source produces values based on
* requests when it is active but more values are available even after its completion.
* In this case, the onComplete() can't just emit the contents of the queue but has to
* coordinate with the requested amounts. This requires two distinct modes: active and
* completed. In active mode, requests flow through and the queue is not accessed but
* in completed mode, requests no-longer reach the upstream but help in draining the queue.
*
* @param <T> the value type emitted
* @param n
* @param actual
* @param queue
* @param state
* @param isCancelled
* @return true if the state indicates a completion state.
*/
public static <T> boolean postCompleteRequest(long n,
Subscriber<? super T> actual,
Queue<T> queue,
AtomicLong state,
BooleanSupplier isCancelled) {
for (; ; ) {
long r = state.get();
// extract the current request amount
long r0 = r & REQUESTED_MASK;
// preserve COMPLETED_MASK and calculate new requested amount
long u = (r & COMPLETED_MASK) | BackpressureHelper.addCap(r0, n);
if (state.compareAndSet(r, u)) {
// (complete, 0) -> (complete, n) transition then replay
if (r == COMPLETED_MASK) {
postCompleteDrain(n | COMPLETED_MASK, actual, queue, state, isCancelled);
return true;
}
// (active, r) -> (active, r + n) transition then continue with requesting from upstream
return false;
}
}
}
static boolean isCancelled(BooleanSupplier cancelled) {
try {
return cancelled.getAsBoolean();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
return true;
}
}
/**
* Drains the queue based on the outstanding requests in post-completed mode (only!).
*
* @param n
* @param actual
* @param queue
* @param state
* @param isCancelled
* @return true if the queue was completely drained or the drain process was cancelled
*/
static <T> boolean postCompleteDrain(long n,
Subscriber<? super T> actual,
Queue<T> queue,
AtomicLong state,
BooleanSupplier isCancelled) {
// TODO enable fast-path
// if (n == -1 || n == Long.MAX_VALUE) {
// for (;;) {
// if (isCancelled.getAsBoolean()) {
// break;
// }
//
// T v = queue.poll();
//
// if (v == null) {
// actual.onComplete();
// break;
// }
//
// actual.onNext(v);
// }
//
// return true;
// }
long e = n & COMPLETED_MASK;
for (; ; ) {
while (e != n) {
if (isCancelled(isCancelled)) {
return true;
}
T t = queue.poll();
if (t == null) {
actual.onComplete();
return true;
}
actual.onNext(t);
e++;
}
if (isCancelled(isCancelled)) {
return true;
}
if (queue.isEmpty()) {
actual.onComplete();
return true;
}
n = state.get();
if (n == e) {
n = state.addAndGet(-(e & REQUESTED_MASK));
if ((n & REQUESTED_MASK) == 0L) {
return false;
}
e = n & COMPLETED_MASK;
}
}
}
/**
* Signals the completion of the main sequence and switches to post-completion replay mode.
*
* <p>
* Don't modify the queue after calling this method!
*
* <p>
* Post-completion backpressure handles the case when a source produces values based on
* requests when it is active but more values are available even after its completion.
* In this case, the onCompleted() can't just emit the contents of the queue but has to
* coordinate with the requested amounts. This requires two distinct modes: active and
* completed. In active mode, requests flow through and the queue is not accessed but
* in completed mode, requests no-longer reach the upstream but help in draining the queue.
* <p>
* The algorithm utilizes the most significant bit (bit 63) of a long value (AtomicLong) since
* request amount only goes up to Long.MAX_VALUE (bits 0-62) and negative values aren't
* allowed.
*
* @param <T> the value type emitted
* @param actual
* @param queue
* @param state
* @param isCancelled
*/
public static <T> void postComplete(Subscriber<? super T> actual,
Queue<T> queue,
AtomicLong state,
BooleanSupplier isCancelled) {
if (queue.isEmpty()) {
actual.onComplete();
return;
}
if (postCompleteDrain(state.get(), actual, queue, state, isCancelled)) {
return;
}
for (; ; ) {
long r = state.get();
if ((r & COMPLETED_MASK) != 0L) {
return;
}
long u = r | COMPLETED_MASK;
// (active, r) -> (complete, r) transition
if (state.compareAndSet(r, u)) {
// if the requested amount was non-zero, drain the queue
if (r != 0L) {
postCompleteDrain(u, actual, queue, state, isCancelled);
}
return;
}
}
}
}