-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
Copy pathQueueDrainHelper.java
490 lines (414 loc) · 15.6 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
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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.AtomicLong;
import org.reactivestreams.*;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.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 final class QueueDrainHelper {
/** Utility class. */
private QueueDrainHelper() {
throw new IllegalStateException("No instances!");
}
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) {
qd.produced(1);
}
}
} else {
q.clear();
if (dispose != null) {
dispose.dispose();
}
a.onError(new MissingBackpressureException("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, ObservableQueueDrain<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, ObservableQueueDrain<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, negative value will create an array-based SPSC queue
* @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 (not 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 the request amount, positive (not validated)
* @param actual the target Subscriber to send events to
* @param queue the queue to drain if in the post-complete state
* @param state holds the request amount and the post-completed flag
* @param isCancelled a supplier that returns true if the drain has been cancelled
* @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 the current request amount
* @param actual the target Subscriber to send events to
* @param queue the queue to drain if in the post-complete state
* @param state holds the request amount and the post-completed flag
* @param isCancelled a supplier that returns true if the drain has been cancelled
* @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 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.
* <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 the target Subscriber to send events to
* @param queue the queue to drain if in the post-complete state
* @param state holds the request amount and the post-completed flag
* @param isCancelled a supplier that returns true if the drain has been cancelled
*/
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;
}
}
}
}