Debian Codegraph @

src/main/java/io/reactivex/rxjava3/processors/UnicastProcessor.java

raw
1 /*
2 * Copyright (c) 2016-present, RxJava Contributors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
11 * the License for the specific language governing permissions and limitations under the License.
12 */
13
14 package io.reactivex.rxjava3.processors;
15
16 import java.util.Objects;
17 import java.util.concurrent.atomic.*;
18
19 import org.reactivestreams.*;
20
21 import io.reactivex.rxjava3.annotations.*;
22 import io.reactivex.rxjava3.internal.functions.*;
23 import io.reactivex.rxjava3.internal.subscriptions.*;
24 import io.reactivex.rxjava3.internal.util.*;
25 import io.reactivex.rxjava3.operators.QueueSubscription;
26 import io.reactivex.rxjava3.operators.SpscLinkedArrayQueue;
27 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
28
29 /**
30 * A {@link FlowableProcessor} variant that queues up events until a single {@link Subscriber} subscribes to it, replays
31 * those events to it until the {@code Subscriber} catches up and then switches to relaying events live to
32 * this single {@code Subscriber} until this {@code UnicastProcessor} terminates or the {@code Subscriber} cancels
33 * its subscription.
34 * <p>
35 * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/UnicastProcessor.png" alt="">
36 * <p>
37 * This processor does not have a public constructor by design; a new empty instance of this
38 * {@code UnicastProcessor} can be created via the following {@code create} methods that
39 * allow specifying the retention policy for items:
40 * <ul>
41 * <li>{@link #create()} - creates an empty, unbounded {@code UnicastProcessor} that
42 * caches all items and the terminal event it receives.</li>
43 * <li>{@link #create(int)} - creates an empty, unbounded {@code UnicastProcessor}
44 * with a hint about how many <b>total</b> items one expects to retain.</li>
45 * <li>{@link #create(boolean)} - creates an empty, unbounded {@code UnicastProcessor} that
46 * optionally delays an error it receives and replays it after the regular items have been emitted.</li>
47 * <li>{@link #create(int, Runnable)} - creates an empty, unbounded {@code UnicastProcessor}
48 * with a hint about how many <b>total</b> items one expects to retain and a callback that will be
49 * called exactly once when the {@code UnicastProcessor} gets terminated or the single {@code Subscriber} cancels.</li>
50 * <li>{@link #create(int, Runnable, boolean)} - creates an empty, unbounded {@code UnicastProcessor}
51 * with a hint about how many <b>total</b> items one expects to retain and a callback that will be
52 * called exactly once when the {@code UnicastProcessor} gets terminated or the single {@code Subscriber} cancels
53 * and optionally delays an error it receives and replays it after the regular items have been emitted.</li>
54 * </ul>
55 * <p>
56 * If more than one {@code Subscriber} attempts to subscribe to this Processor, they
57 * will receive an {@link IllegalStateException} if this {@link UnicastProcessor} hasn't terminated yet,
58 * or the Subscribers receive the terminal event (error or completion) if this
59 * Processor has terminated.
60 * <p>
61 * The {@code UnicastProcessor} buffers notifications and replays them to the single {@code Subscriber} as requested,
62 * for which it holds upstream items an unbounded internal buffer until they can be emitted.
63 * <p>
64 * Since a {@code UnicastProcessor} is a Reactive Streams {@code Processor},
65 * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as
66 * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a
67 * {@link NullPointerException} being thrown and the processor's state is not changed.
68 * <p>
69 * Since a {@code UnicastProcessor} is a {@link io.reactivex.rxjava3.core.Flowable} as well as a {@link FlowableProcessor}, it
70 * honors the downstream backpressure but consumes an upstream source in an unbounded manner (requesting {@link Long#MAX_VALUE}).
71 * <p>
72 * When this {@code UnicastProcessor} is terminated via {@link #onError(Throwable)} the current or late single {@code Subscriber}
73 * may receive the {@code Throwable} before any available items could be emitted. To make sure an {@code onError} event is delivered
74 * to the {@code Subscriber} after the normal items, create a {@code UnicastProcessor} with the {@link #create(boolean)} or
75 * {@link #create(int, Runnable, boolean)} factory methods.
76 * <p>
77 * Even though {@code UnicastProcessor} implements the {@code Subscriber} interface, calling
78 * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>)
79 * if the processor is used as a standalone source. However, calling {@code onSubscribe}
80 * after the {@code UnicastProcessor} reached its terminal state will result in the
81 * given {@code Subscription} being canceled immediately.
82 * <p>
83 * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()}
84 * is required to be serialized (called from the same thread or called non-overlappingly from different threads
85 * through external means of serialization). The {@link #toSerialized()} method available to all {@link FlowableProcessor}s
86 * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber}
87 * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively).
88 * <p>
89 * This {@code UnicastProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()},
90 * {@link #getThrowable()} and {@link #hasSubscribers()}.
91 * <dl>
92 * <dt><b>Backpressure:</b></dt>
93 * <dd>{@code UnicastProcessor} honors the downstream backpressure but consumes an upstream source
94 * (if any) in an unbounded manner (requesting {@link Long#MAX_VALUE}).</dd>
95 * <dt><b>Scheduler:</b></dt>
96 * <dd>{@code UnicastProcessor} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and
97 * the single {@code Subscriber} gets notified on the thread the respective {@code onXXX} methods were invoked.</dd>
98 * <dt><b>Error handling:</b></dt>
99 * <dd>When the {@link #onError(Throwable)} is called, the {@code UnicastProcessor} enters into a terminal state
100 * and emits the same {@code Throwable} instance to the current single {@code Subscriber}. During this emission,
101 * if the single {@code Subscriber}s cancels its respective {@code Subscription}s, the
102 * {@code Throwable} is delivered to the global error handler via
103 * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)}.
104 * If there were no {@code Subscriber}s subscribed to this {@code UnicastProcessor} when the {@code onError()}
105 * was called, the global error handler is not invoked.
106 * </dd>
107 * </dl>
108 * <p>
109 * Example usage:
110 * <pre><code>
111 * UnicastProcessor&lt;Integer&gt; processor = UnicastProcessor.create();
112 *
113 * TestSubscriber&lt;Integer&gt; ts1 = processor.test();
114 *
115 * // fresh UnicastProcessors are empty
116 * ts1.assertEmpty();
117 *
118 * TestSubscriber&lt;Integer&gt; ts2 = processor.test();
119 *
120 * // A UnicastProcessor only allows one Subscriber during its lifetime
121 * ts2.assertFailure(IllegalStateException.class);
122 *
123 * processor.onNext(1);
124 * ts1.assertValue(1);
125 *
126 * processor.onNext(2);
127 * ts1.assertValues(1, 2);
128 *
129 * processor.onComplete();
130 * ts1.assertResult(1, 2);
131 *
132 * // ----------------------------------------------------
133 *
134 * UnicastProcessor&lt;Integer&gt; processor2 = UnicastProcessor.create();
135 *
136 * // a UnicastProcessor caches events until its single Subscriber subscribes
137 * processor2.onNext(1);
138 * processor2.onNext(2);
139 * processor2.onComplete();
140 *
141 * TestSubscriber&lt;Integer&gt; ts3 = processor2.test();
142 *
143 * // the cached events are emitted in order
144 * ts3.assertResult(1, 2);
145 * </code></pre>
146 *
147 * @param <T> the value type received and emitted by this Processor subclass
148 * @since 2.0
149 */
150 public final class UnicastProcessor<@NonNull T> extends FlowableProcessor<T> {
151
152 final SpscLinkedArrayQueue<T> queue;
153
154 final AtomicReference<Runnable> onTerminate;
155
156 final boolean delayError;
157
158 volatile boolean done;
159
160 Throwable error;
161
162 final AtomicReference<Subscriber<? super T>> downstream;
163
164 volatile boolean cancelled;
165
166 final AtomicBoolean once;
167
168 final BasicIntQueueSubscription<T> wip;
169
170 final AtomicLong requested;
171
172 boolean enableOperatorFusion;
173
174 /**
175 * Creates an UnicastSubject with an internal buffer capacity hint 16.
176 * @param <T> the value type
177 * @return an UnicastSubject instance
178 */
179 @CheckReturnValue
180 @NonNull
181 public static <T> UnicastProcessor<T> create() {
182 return new UnicastProcessor<>(bufferSize(), null, true);
183 }
184
185 /**
186 * Creates an UnicastProcessor with the given internal buffer capacity hint.
187 * @param <T> the value type
188 * @param capacityHint the hint to size the internal unbounded buffer
189 * @return an UnicastProcessor instance
190 * @throws IllegalArgumentException if {@code capacityHint} is non-positive
191 */
192 @CheckReturnValue
193 @NonNull
194 public static <T> UnicastProcessor<T> create(int capacityHint) {
195 ObjectHelper.verifyPositive(capacityHint, "capacityHint");
196 return new UnicastProcessor<>(capacityHint, null, true);
197 }
198
199 /**
200 * Creates an UnicastProcessor with default internal buffer capacity hint and delay error flag.
201 * <p>History: 2.0.8 - experimental
202 * @param <T> the value type
203 * @param delayError deliver pending onNext events before onError
204 * @return an UnicastProcessor instance
205 * @since 2.2
206 */
207 @CheckReturnValue
208 @NonNull
209 public static <T> UnicastProcessor<T> create(boolean delayError) {
210 return new UnicastProcessor<>(bufferSize(), null, delayError);
211 }
212
213 /**
214 * Creates an UnicastProcessor with the given internal buffer capacity hint and a callback for
215 * the case when the single Subscriber cancels its subscription or the
216 * processor is terminated.
217 *
218 * <p>The callback, if not null, is called exactly once and
219 * non-overlapped with any active replay.
220 *
221 * @param <T> the value type
222 * @param capacityHint the hint to size the internal unbounded buffer
223 * @param onTerminate the non null callback
224 * @return an UnicastProcessor instance
225 * @throws NullPointerException if {@code onTerminate} is {@code null}
226 * @throws IllegalArgumentException if {@code capacityHint} is non-positive
227 */
228 @CheckReturnValue
229 @NonNull
230 public static <T> UnicastProcessor<T> create(int capacityHint, @NonNull Runnable onTerminate) {
231 return create(capacityHint, onTerminate, true);
232 }
233
234 /**
235 * Creates an UnicastProcessor with the given internal buffer capacity hint, delay error flag and a callback for
236 * the case when the single Subscriber cancels its subscription or
237 * the processor is terminated.
238 *
239 * <p>The callback, if not null, is called exactly once and
240 * non-overlapped with any active replay.
241 * <p>History: 2.0.8 - experimental
242 * @param <T> the value type
243 * @param capacityHint the hint to size the internal unbounded buffer
244 * @param onTerminate the non null callback
245 * @param delayError deliver pending onNext events before onError
246 * @return an UnicastProcessor instance
247 * @throws NullPointerException if {@code onTerminate} is {@code null}
248 * @throws IllegalArgumentException if {@code capacityHint} is non-positive
249 * @since 2.2
250 */
251 @CheckReturnValue
252 @NonNull
253 public static <T> UnicastProcessor<T> create(int capacityHint, @NonNull Runnable onTerminate, boolean delayError) {
254 Objects.requireNonNull(onTerminate, "onTerminate");
255 ObjectHelper.verifyPositive(capacityHint, "capacityHint");
256 return new UnicastProcessor<>(capacityHint, onTerminate, delayError);
257 }
258
259 /**
260 * Creates an UnicastProcessor with the given capacity hint and callback
261 * for when the Processor is terminated normally or its single Subscriber cancels.
262 * <p>History: 2.0.8 - experimental
263 * @param capacityHint the capacity hint for the internal, unbounded queue
264 * @param onTerminate the callback to run when the Processor is terminated or cancelled, null not allowed
265 * @param delayError deliver pending onNext events before onError
266 * @since 2.2
267 */
268 UnicastProcessor(int capacityHint, Runnable onTerminate, boolean delayError) {
269 this.queue = new SpscLinkedArrayQueue<>(capacityHint);
270 this.onTerminate = new AtomicReference<>(onTerminate);
271 this.delayError = delayError;
272 this.downstream = new AtomicReference<>();
273 this.once = new AtomicBoolean();
274 this.wip = new UnicastQueueSubscription();
275 this.requested = new AtomicLong();
276 }
277
278 void doTerminate() {
279 Runnable r = onTerminate.getAndSet(null);
280 if (r != null) {
281 r.run();
282 }
283 }
284
285 void drainRegular(Subscriber<? super T> a) {
286 int missed = 1;
287
288 final SpscLinkedArrayQueue<T> q = queue;
289 final boolean failFast = !delayError;
290 for (;;) {
291
292 long r = requested.get();
293 long e = 0L;
294
295 while (r != e) {
296 boolean d = done;
297
298 T t = q.poll();
299 boolean empty = t == null;
300
301 if (checkTerminated(failFast, d, empty, a, q)) {
302 return;
303 }
304
305 if (empty) {
306 break;
307 }
308
309 a.onNext(t);
310
311 e++;
312 }
313
314 if (r == e && checkTerminated(failFast, done, q.isEmpty(), a, q)) {
315 return;
316 }
317
318 if (e != 0 && r != Long.MAX_VALUE) {
319 requested.addAndGet(-e);
320 }
321
322 missed = wip.addAndGet(-missed);
323 if (missed == 0) {
324 break;
325 }
326 }
327 }
328
329 void drainFused(Subscriber<? super T> a) {
330 int missed = 1;
331
332 final SpscLinkedArrayQueue<T> q = queue;
333 final boolean failFast = !delayError;
334 for (;;) {
335
336 if (cancelled) {
337 downstream.lazySet(null);
338 return;
339 }
340
341 boolean d = done;
342
343 if (failFast && d && error != null) {
344 q.clear();
345 downstream.lazySet(null);
346 a.onError(error);
347 return;
348 }
349 a.onNext(null);
350
351 if (d) {
352 downstream.lazySet(null);
353
354 Throwable ex = error;
355 if (ex != null) {
356 a.onError(ex);
357 } else {
358 a.onComplete();
359 }
360 return;
361 }
362
363 missed = wip.addAndGet(-missed);
364 if (missed == 0) {
365 break;
366 }
367 }
368 }
369
370 void drain() {
371 if (wip.getAndIncrement() != 0) {
372 return;
373 }
374
375 int missed = 1;
376
377 Subscriber<? super T> a = downstream.get();
378 for (;;) {
379 if (a != null) {
380
381 if (enableOperatorFusion) {
382 drainFused(a);
383 } else {
384 drainRegular(a);
385 }
386 return;
387 }
388
389 missed = wip.addAndGet(-missed);
390 if (missed == 0) {
391 break;
392 }
393 a = downstream.get();
394 }
395 }
396
397 boolean checkTerminated(boolean failFast, boolean d, boolean empty, Subscriber<? super T> a, SpscLinkedArrayQueue<T> q) {
398 if (cancelled) {
399 q.clear();
400 downstream.lazySet(null);
401 return true;
402 }
403
404 if (d) {
405 if (failFast && error != null) {
406 q.clear();
407 downstream.lazySet(null);
408 a.onError(error);
409 return true;
410 }
411 if (empty) {
412 Throwable e = error;
413 downstream.lazySet(null);
414 if (e != null) {
415 a.onError(e);
416 } else {
417 a.onComplete();
418 }
419 return true;
420 }
421 }
422
423 return false;
424 }
425
426 @Override
427 public void onSubscribe(Subscription s) {
428 if (done || cancelled) {
429 s.cancel();
430 } else {
431 s.request(Long.MAX_VALUE);
432 }
433 }
434
435 @Override
436 public void onNext(T t) {
437 ExceptionHelper.nullCheck(t, "onNext called with a null value.");
438
439 if (done || cancelled) {
440 return;
441 }
442
443 queue.offer(t);
444 drain();
445 }
446
447 @Override
448 public void onError(Throwable t) {
449 ExceptionHelper.nullCheck(t, "onError called with a null Throwable.");
450
451 if (done || cancelled) {
452 RxJavaPlugins.onError(t);
453 return;
454 }
455
456 error = t;
457 done = true;
458
459 doTerminate();
460
461 drain();
462 }
463
464 @Override
465 public void onComplete() {
466 if (done || cancelled) {
467 return;
468 }
469
470 done = true;
471
472 doTerminate();
473
474 drain();
475 }
476
477 @Override
478 protected void subscribeActual(Subscriber<? super T> s) {
479 if (!once.get() && once.compareAndSet(false, true)) {
480
481 s.onSubscribe(wip);
482 downstream.set(s);
483 if (cancelled) {
484 downstream.lazySet(null);
485 } else {
486 drain();
487 }
488 } else {
489 EmptySubscription.error(new IllegalStateException("This processor allows only a single Subscriber"), s);
490 }
491 }
492
493 final class UnicastQueueSubscription extends BasicIntQueueSubscription<T> {
494
495 private static final long serialVersionUID = -4896760517184205454L;
496
497 @Nullable
498 @Override
499 public T poll() {
500 return queue.poll();
501 }
502
503 @Override
504 public boolean isEmpty() {
505 return queue.isEmpty();
506 }
507
508 @Override
509 public void clear() {
510 queue.clear();
511 }
512
513 @Override
514 public int requestFusion(int requestedMode) {
515 if ((requestedMode & QueueSubscription.ASYNC) != 0) {
516 enableOperatorFusion = true;
517 return QueueSubscription.ASYNC;
518 }
519 return QueueSubscription.NONE;
520 }
521
522 @Override
523 public void request(long n) {
524 if (SubscriptionHelper.validate(n)) {
525 BackpressureHelper.add(requested, n);
526 drain();
527 }
528 }
529
530 @Override
531 public void cancel() {
532 if (cancelled) {
533 return;
534 }
535 cancelled = true;
536
537 doTerminate();
538
539 downstream.lazySet(null);
540 if (wip.getAndIncrement() == 0) {
541 downstream.lazySet(null);
542 if (!enableOperatorFusion) {
543 queue.clear();
544 }
545 }
546 }
547 }
548
549 @Override
550 @CheckReturnValue
551 public boolean hasSubscribers() {
552 return downstream.get() != null;
553 }
554
555 @Override
556 @Nullable
557 @CheckReturnValue
558 public Throwable getThrowable() {
559 if (done) {
560 return error;
561 }
562 return null;
563 }
564
565 @Override
566 @CheckReturnValue
567 public boolean hasComplete() {
568 return done && error == null;
569 }
570
571 @Override
572 @CheckReturnValue
573 public boolean hasThrowable() {
574 return done && error != null;
575 }
576 }