Debian Codegraph @

src/main/java/io/reactivex/rxjava3/processors/BehaviorProcessor.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 import java.util.concurrent.locks.*;
19
20 import org.reactivestreams.*;
21
22 import io.reactivex.rxjava3.annotations.*;
23 import io.reactivex.rxjava3.exceptions.MissingBackpressureException;
24 import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
25 import io.reactivex.rxjava3.internal.util.*;
26 import io.reactivex.rxjava3.internal.util.AppendOnlyLinkedArrayList.NonThrowingPredicate;
27 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
28
29 /**
30 * Processor that emits the most recent item it has observed and all subsequent observed items to each subscribed
31 * {@link Subscriber}.
32 * <p>
33 * <img width="640" height="460" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/S.BehaviorProcessor.png" alt="">
34 * <p>
35 * This processor does not have a public constructor by design; a new empty instance of this
36 * {@code BehaviorProcessor} can be created via the {@link #create()} method and
37 * a new non-empty instance can be created via {@link #createDefault(Object)} (named as such to avoid
38 * overload resolution conflict with {@code Flowable.create} that creates a Flowable, not a {@code BehaviorProcessor}).
39 * <p>
40 * In accordance with the Reactive Streams specification (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>)
41 * {@code null}s are not allowed as default initial values in {@link #createDefault(Object)} or as parameters to {@link #onNext(Object)} and
42 * {@link #onError(Throwable)}.
43 * <p>
44 * When this {@code BehaviorProcessor} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, the
45 * last observed item (if any) is cleared and late {@link org.reactivestreams.Subscriber}s only receive
46 * the respective terminal event.
47 * <p>
48 * The {@code BehaviorProcessor} does not support clearing its cached value (to appear empty again), however, the
49 * effect can be achieved by using a special item and making sure {@code Subscriber}s subscribe through a
50 * filter whose predicate filters out this special item:
51 * <pre><code>
52 * BehaviorProcessor&lt;Integer&gt; processor = BehaviorProcessor.create();
53 *
54 * final Integer EMPTY = Integer.MIN_VALUE;
55 *
56 * Flowable&lt;Integer&gt; flowable = processor.filter(v -&gt; v != EMPTY);
57 *
58 * TestSubscriber&lt;Integer&gt; ts1 = flowable.test();
59 *
60 * processor.onNext(1);
61 * // this will "clear" the cache
62 * processor.onNext(EMPTY);
63 *
64 * TestSubscriber&lt;Integer&gt; ts2 = flowable.test();
65 *
66 * processor.onNext(2);
67 * processor.onComplete();
68 *
69 * // ts1 received both non-empty items
70 * ts1.assertResult(1, 2);
71 *
72 * // ts2 received only 2 even though the current item was EMPTY
73 * // when it got subscribed
74 * ts2.assertResult(2);
75 *
76 * // Subscribers coming after the processor was terminated receive
77 * // no items and only the onComplete event in this case.
78 * flowable.test().assertResult();
79 * </code></pre>
80 * <p>
81 * Even though {@code BehaviorProcessor} implements the {@code Subscriber} interface, calling
82 * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>)
83 * if the processor is used as a standalone source. However, calling {@code onSubscribe}
84 * after the {@code BehaviorProcessor} reached its terminal state will result in the
85 * given {@code Subscription} being cancelled immediately.
86 * <p>
87 * Calling {@link #onNext(Object)}, {@link #offer(Object)}, {@link #onError(Throwable)} and {@link #onComplete()}
88 * is required to be serialized (called from the same thread or called non-overlappingly from different threads
89 * through external means of serialization). The {@link #toSerialized()} method available to all {@code FlowableProcessor}s
90 * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber}
91 * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively).
92 * Note that serializing over {@link #offer(Object)} is not supported through {@code toSerialized()} because it is a method
93 * available on the {@code PublishProcessor} and {@code BehaviorProcessor} classes only.
94 * <p>
95 * This {@code BehaviorProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()},
96 * {@link #getThrowable()} and {@link #hasSubscribers()} as well as means to read the latest observed value
97 * in a non-blocking and thread-safe manner via {@link #hasValue()} or {@link #getValue()}.
98 * <p>
99 * Note that this processor signals {@code MissingBackpressureException} if a particular {@code Subscriber} is not
100 * ready to receive {@code onNext} events. To avoid this exception being signaled, use {@link #offer(Object)} to only
101 * try to emit an item when all {@code Subscriber}s have requested item(s).
102 * <dl>
103 * <dt><b>Backpressure:</b></dt>
104 * <dd>The {@code BehaviorProcessor} does not coordinate requests of its downstream {@code Subscriber}s and
105 * expects each individual {@code Subscriber} is ready to receive {@code onNext} items when {@link #onNext(Object)}
106 * is called. If a {@code Subscriber} is not ready, a {@code MissingBackpressureException} is signalled to it.
107 * To avoid overflowing the current {@code Subscriber}s, the conditional {@link #offer(Object)} method is available
108 * that returns true if any of the {@code Subscriber}s is not ready to receive {@code onNext} events. If
109 * there are no {@code Subscriber}s to the processor, {@code offer()} always succeeds.
110 * If the {@code BehaviorProcessor} is (optionally) subscribed to another {@code Publisher}, this upstream
111 * {@code Publisher} is consumed in an unbounded fashion (requesting {@link Long#MAX_VALUE}).</dd>
112 * <dt><b>Scheduler:</b></dt>
113 * <dd>{@code BehaviorProcessor} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and
114 * the {@code Subscriber}s get notified on the thread the respective {@code onXXX} methods were invoked.</dd>
115 * <dt><b>Error handling:</b></dt>
116 * <dd>When the {@link #onError(Throwable)} is called, the {@code BehaviorProcessor} enters into a terminal state
117 * and emits the same {@code Throwable} instance to the last set of {@code Subscriber}s. During this emission,
118 * if one or more {@code Subscriber}s cancel their respective {@code Subscription}s, the
119 * {@code Throwable} is delivered to the global error handler via
120 * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Subscriber}s
121 * cancel at once).
122 * If there were no {@code Subscriber}s subscribed to this {@code BehaviorProcessor} when the {@code onError()}
123 * was called, the global error handler is not invoked.
124 * </dd>
125 * </dl>
126 * <p>
127 * Example usage:
128 * <pre> {@code
129
130 // subscriber will receive all events.
131 BehaviorProcessor<Object> processor = BehaviorProcessor.create("default");
132 processor.subscribe(subscriber);
133 processor.onNext("one");
134 processor.onNext("two");
135 processor.onNext("three");
136
137 // subscriber will receive the "one", "two" and "three" events, but not "zero"
138 BehaviorProcessor<Object> processor = BehaviorProcessor.create("default");
139 processor.onNext("zero");
140 processor.onNext("one");
141 processor.subscribe(subscriber);
142 processor.onNext("two");
143 processor.onNext("three");
144
145 // subscriber will receive only onComplete
146 BehaviorProcessor<Object> processor = BehaviorProcessor.create("default");
147 processor.onNext("zero");
148 processor.onNext("one");
149 processor.onComplete();
150 processor.subscribe(subscriber);
151
152 // subscriber will receive only onError
153 BehaviorProcessor<Object> processor = BehaviorProcessor.create("default");
154 processor.onNext("zero");
155 processor.onNext("one");
156 processor.onError(new RuntimeException("error"));
157 processor.subscribe(subscriber);
158 } </pre>
159 *
160 * @param <T>
161 * the type of item expected to be observed and emitted by the Processor
162 */
163 public final class BehaviorProcessor<@NonNull T> extends FlowableProcessor<T> {
164 final AtomicReference<BehaviorSubscription<T>[]> subscribers;
165
166 static final Object[] EMPTY_ARRAY = new Object[0];
167
168 @SuppressWarnings("rawtypes")
169 static final BehaviorSubscription[] EMPTY = new BehaviorSubscription[0];
170
171 @SuppressWarnings("rawtypes")
172 static final BehaviorSubscription[] TERMINATED = new BehaviorSubscription[0];
173
174 final ReadWriteLock lock;
175 final Lock readLock;
176 final Lock writeLock;
177
178 final AtomicReference<Object> value;
179
180 final AtomicReference<Throwable> terminalEvent;
181
182 long index;
183
184 /**
185 * Creates a {@link BehaviorProcessor} without a default item.
186 *
187 * @param <T>
188 * the type of item the BehaviorProcessor will emit
189 * @return the constructed {@link BehaviorProcessor}
190 */
191 @CheckReturnValue
192 @NonNull
193 public static <T> BehaviorProcessor<T> create() {
194 return new BehaviorProcessor<>();
195 }
196
197 /**
198 * Creates a {@link BehaviorProcessor} that emits the last item it observed and all subsequent items to each
199 * {@link Subscriber} that subscribes to it.
200 *
201 * @param <T>
202 * the type of item the BehaviorProcessor will emit
203 * @param defaultValue
204 * the item that will be emitted first to any {@link Subscriber} as long as the
205 * {@link BehaviorProcessor} has not yet observed any items from its source {@code Observable}
206 * @return the constructed {@link BehaviorProcessor}
207 * @throws NullPointerException if {@code defaultValue} is {@code null}
208 */
209 @CheckReturnValue
210 @NonNull
211 public static <@NonNull T> BehaviorProcessor<T> createDefault(T defaultValue) {
212 Objects.requireNonNull(defaultValue, "defaultValue is null");
213 return new BehaviorProcessor<>(defaultValue);
214 }
215
216 /**
217 * Constructs an empty BehaviorProcessor.
218 * @since 2.0
219 */
220 @SuppressWarnings("unchecked")
221 BehaviorProcessor() {
222 this.value = new AtomicReference<>();
223 this.lock = new ReentrantReadWriteLock();
224 this.readLock = lock.readLock();
225 this.writeLock = lock.writeLock();
226 this.subscribers = new AtomicReference<>(EMPTY);
227 this.terminalEvent = new AtomicReference<>();
228 }
229
230 /**
231 * Constructs a BehaviorProcessor with the given initial value.
232 * @param defaultValue the initial value, not null (verified)
233 * @throws NullPointerException if {@code defaultValue} is {@code null}
234 * @since 2.0
235 */
236 BehaviorProcessor(T defaultValue) {
237 this();
238 this.value.lazySet(defaultValue);
239 }
240
241 @Override
242 protected void subscribeActual(@NonNull Subscriber<? super T> s) {
243 BehaviorSubscription<T> bs = new BehaviorSubscription<>(s, this);
244 s.onSubscribe(bs);
245 if (add(bs)) {
246 if (bs.cancelled) {
247 remove(bs);
248 } else {
249 bs.emitFirst();
250 }
251 } else {
252 Throwable ex = terminalEvent.get();
253 if (ex == ExceptionHelper.TERMINATED) {
254 s.onComplete();
255 } else {
256 s.onError(ex);
257 }
258 }
259 }
260
261 @Override
262 public void onSubscribe(@NonNull Subscription s) {
263 if (terminalEvent.get() != null) {
264 s.cancel();
265 return;
266 }
267 s.request(Long.MAX_VALUE);
268 }
269
270 @Override
271 public void onNext(@NonNull T t) {
272 ExceptionHelper.nullCheck(t, "onNext called with a null value.");
273
274 if (terminalEvent.get() != null) {
275 return;
276 }
277 Object o = NotificationLite.next(t);
278 setCurrent(o);
279 for (BehaviorSubscription<T> bs : subscribers.get()) {
280 bs.emitNext(o, index);
281 }
282 }
283
284 @Override
285 public void onError(@NonNull Throwable t) {
286 ExceptionHelper.nullCheck(t, "onError called with a null Throwable.");
287 if (!terminalEvent.compareAndSet(null, t)) {
288 RxJavaPlugins.onError(t);
289 return;
290 }
291 Object o = NotificationLite.error(t);
292 for (BehaviorSubscription<T> bs : terminate(o)) {
293 bs.emitNext(o, index);
294 }
295 }
296
297 @Override
298 public void onComplete() {
299 if (!terminalEvent.compareAndSet(null, ExceptionHelper.TERMINATED)) {
300 return;
301 }
302 Object o = NotificationLite.complete();
303 for (BehaviorSubscription<T> bs : terminate(o)) {
304 bs.emitNext(o, index); // relaxed read okay since this is the only mutator thread
305 }
306 }
307
308 /**
309 * Tries to emit the item to all currently subscribed {@link Subscriber}s if all of them
310 * has requested some value, returns {@code false} otherwise.
311 * <p>
312 * This method should be called in a sequential manner just like the {@code onXXX} methods
313 * of this {@code BehaviorProcessor}.
314 * <p>History: 2.0.8 - experimental
315 * @param t the item to emit, not {@code null}
316 * @return {@code true} if the item was emitted to all {@code Subscriber}s
317 * @throws NullPointerException if {@code t} is {@code null}
318 * @since 2.2
319 */
320 @CheckReturnValue
321 public boolean offer(@NonNull T t) {
322 ExceptionHelper.nullCheck(t, "offer called with a null value.");
323
324 BehaviorSubscription<T>[] array = subscribers.get();
325
326 for (BehaviorSubscription<T> s : array) {
327 if (s.isFull()) {
328 return false;
329 }
330 }
331
332 Object o = NotificationLite.next(t);
333 setCurrent(o);
334 for (BehaviorSubscription<T> bs : array) {
335 bs.emitNext(o, index);
336 }
337 return true;
338 }
339
340 @Override
341 @CheckReturnValue
342 public boolean hasSubscribers() {
343 return subscribers.get().length != 0;
344 }
345
346 @CheckReturnValue
347 /* test support*/ int subscriberCount() {
348 return subscribers.get().length;
349 }
350
351 @Override
352 @Nullable
353 @CheckReturnValue
354 public Throwable getThrowable() {
355 Object o = value.get();
356 if (NotificationLite.isError(o)) {
357 return NotificationLite.getError(o);
358 }
359 return null;
360 }
361
362 /**
363 * Returns a single value the BehaviorProcessor currently has or null if no such value exists.
364 * <p>The method is thread-safe.
365 * @return a single value the BehaviorProcessor currently has or null if no such value exists
366 */
367 @Nullable
368 @CheckReturnValue
369 public T getValue() {
370 Object o = value.get();
371 if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) {
372 return null;
373 }
374 return NotificationLite.getValue(o);
375 }
376
377 @Override
378 @CheckReturnValue
379 public boolean hasComplete() {
380 Object o = value.get();
381 return NotificationLite.isComplete(o);
382 }
383
384 @Override
385 @CheckReturnValue
386 public boolean hasThrowable() {
387 Object o = value.get();
388 return NotificationLite.isError(o);
389 }
390
391 /**
392 * Returns true if the BehaviorProcessor has any value.
393 * <p>The method is thread-safe.
394 * @return true if the BehaviorProcessor has any value
395 */
396 @CheckReturnValue
397 public boolean hasValue() {
398 Object o = value.get();
399 return o != null && !NotificationLite.isComplete(o) && !NotificationLite.isError(o);
400 }
401
402 boolean add(BehaviorSubscription<T> rs) {
403 for (;;) {
404 BehaviorSubscription<T>[] a = subscribers.get();
405 if (a == TERMINATED) {
406 return false;
407 }
408 int len = a.length;
409 @SuppressWarnings("unchecked")
410 BehaviorSubscription<T>[] b = new BehaviorSubscription[len + 1];
411 System.arraycopy(a, 0, b, 0, len);
412 b[len] = rs;
413 if (subscribers.compareAndSet(a, b)) {
414 return true;
415 }
416 }
417 }
418
419 @SuppressWarnings("unchecked")
420 void remove(BehaviorSubscription<T> rs) {
421 for (;;) {
422 BehaviorSubscription<T>[] a = subscribers.get();
423 int len = a.length;
424 if (len == 0) {
425 return;
426 }
427 int j = -1;
428 for (int i = 0; i < len; i++) {
429 if (a[i] == rs) {
430 j = i;
431 break;
432 }
433 }
434
435 if (j < 0) {
436 return;
437 }
438 BehaviorSubscription<T>[] b;
439 if (len == 1) {
440 b = EMPTY;
441 } else {
442 b = new BehaviorSubscription[len - 1];
443 System.arraycopy(a, 0, b, 0, j);
444 System.arraycopy(a, j + 1, b, j, len - j - 1);
445 }
446 if (subscribers.compareAndSet(a, b)) {
447 return;
448 }
449 }
450 }
451
452 @SuppressWarnings("unchecked")
453 BehaviorSubscription<T>[] terminate(Object terminalValue) {
454
455 setCurrent(terminalValue);
456
457 return subscribers.getAndSet(TERMINATED);
458 }
459
460 void setCurrent(Object o) {
461 Lock wl = writeLock;
462 wl.lock();
463 index++;
464 value.lazySet(o);
465 wl.unlock();
466 }
467
468 static final class BehaviorSubscription<@NonNull T> extends AtomicLong implements Subscription, NonThrowingPredicate<Object> {
469
470 private static final long serialVersionUID = 3293175281126227086L;
471
472 final Subscriber<? super T> downstream;
473 final BehaviorProcessor<T> state;
474
475 boolean next;
476 boolean emitting;
477 AppendOnlyLinkedArrayList<Object> queue;
478
479 boolean fastPath;
480
481 volatile boolean cancelled;
482
483 long index;
484
485 BehaviorSubscription(Subscriber<? super T> actual, BehaviorProcessor<T> state) {
486 this.downstream = actual;
487 this.state = state;
488 }
489
490 @Override
491 public void request(long n) {
492 if (SubscriptionHelper.validate(n)) {
493 BackpressureHelper.add(this, n);
494 }
495 }
496
497 @Override
498 public void cancel() {
499 if (!cancelled) {
500 cancelled = true;
501
502 state.remove(this);
503 }
504 }
505
506 void emitFirst() {
507 if (cancelled) {
508 return;
509 }
510 Object o;
511 synchronized (this) {
512 if (cancelled) {
513 return;
514 }
515 if (next) {
516 return;
517 }
518
519 BehaviorProcessor<T> s = state;
520
521 Lock readLock = s.readLock;
522 readLock.lock();
523 index = s.index;
524 o = s.value.get();
525 readLock.unlock();
526
527 emitting = o != null;
528 next = true;
529 }
530
531 if (o != null) {
532 if (test(o)) {
533 return;
534 }
535
536 emitLoop();
537 }
538 }
539
540 void emitNext(Object value, long stateIndex) {
541 if (cancelled) {
542 return;
543 }
544 if (!fastPath) {
545 synchronized (this) {
546 if (cancelled) {
547 return;
548 }
549 if (index == stateIndex) {
550 return;
551 }
552 if (emitting) {
553 AppendOnlyLinkedArrayList<Object> q = queue;
554 if (q == null) {
555 q = new AppendOnlyLinkedArrayList<>(4);
556 queue = q;
557 }
558 q.add(value);
559 return;
560 }
561 next = true;
562 }
563 fastPath = true;
564 }
565
566 test(value);
567 }
568
569 @Override
570 public boolean test(Object o) {
571 if (cancelled) {
572 return true;
573 }
574
575 if (NotificationLite.isComplete(o)) {
576 downstream.onComplete();
577 return true;
578 } else
579 if (NotificationLite.isError(o)) {
580 downstream.onError(NotificationLite.getError(o));
581 return true;
582 }
583
584 long r = get();
585 if (r != 0L) {
586 downstream.onNext(NotificationLite.<T>getValue(o));
587 if (r != Long.MAX_VALUE) {
588 decrementAndGet();
589 }
590 return false;
591 }
592 cancel();
593 downstream.onError(new MissingBackpressureException("Could not deliver value due to lack of requests"));
594 return true;
595 }
596
597 void emitLoop() {
598 for (;;) {
599 if (cancelled) {
600 return;
601 }
602 AppendOnlyLinkedArrayList<Object> q;
603 synchronized (this) {
604 q = queue;
605 if (q == null) {
606 emitting = false;
607 return;
608 }
609 queue = null;
610 }
611
612 q.forEachWhile(this);
613 }
614 }
615
616 public boolean isFull() {
617 return get() == 0L;
618 }
619 }
620 }