Debian Codegraph @

src/main/java/io/reactivex/rxjava3/processors/ReplayProcessor.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.lang.reflect.Array;
17 import java.util.*;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.atomic.*;
20
21 import org.reactivestreams.*;
22
23 import io.reactivex.rxjava3.annotations.*;
24 import io.reactivex.rxjava3.core.Scheduler;
25 import io.reactivex.rxjava3.internal.functions.ObjectHelper;
26 import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
27 import io.reactivex.rxjava3.internal.util.*;
28 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
29
30 /**
31 * Replays events to Subscribers.
32 * <p>
33 * The {@code ReplayProcessor} supports the following item retention strategies:
34 * <ul>
35 * <li>{@link #create()} and {@link #create(int)}: retains and replays all events to current and
36 * future {@code Subscriber}s.
37 * <p>
38 * <img width="640" height="269" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplayProcessor.u.png" alt="">
39 * <p>
40 * <img width="640" height="345" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplayProcessor.ue.png" alt="">
41 * </li>
42 * <li>{@link #createWithSize(int)}: retains at most the given number of items and replays only these
43 * latest items to new {@code Subscriber}s.
44 * <p>
45 * <img width="640" height="332" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplayProcessor.n.png" alt="">
46 * </li>
47 * <li>{@link #createWithTime(long, TimeUnit, Scheduler)}: retains items no older than the specified time
48 * and replays them to new {@code Subscriber}s (which could mean all items age out).
49 * <p>
50 * <img width="640" height="415" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplayProcessor.t.png" alt="">
51 * </li>
52 * <li>{@link #createWithTimeAndSize(long, TimeUnit, Scheduler, int)}: retains no more than the given number of items
53 * which are also no older than the specified time and replays them to new {@code Subscriber}s (which could mean all items age out).
54 * <p>
55 * <img width="640" height="404" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ReplayProcessor.nt.png" alt="">
56 * </li>
57 * </ul>
58 * <p>
59 * The {@code ReplayProcessor} can be created in bounded and unbounded mode. It can be bounded by
60 * size (maximum number of elements retained at most) and/or time (maximum age of elements replayed).
61 * <p>
62 * Since a {@code ReplayProcessor} is a Reactive Streams {@code Processor},
63 * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as
64 * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a
65 * {@link NullPointerException} being thrown and the processor's state is not changed.
66 * <p>
67 * This {@code ReplayProcessor} respects the individual backpressure behavior of its {@code Subscriber}s but
68 * does not coordinate their request amounts towards the upstream (because there might not be any) and
69 * consumes the upstream in an unbounded manner (requesting {@link Long#MAX_VALUE}).
70 * Note that {@code Subscriber}s receive a continuous sequence of values after they subscribed even
71 * if an individual item gets delayed due to backpressure.
72 * Due to concurrency requirements, a size-bounded {@code ReplayProcessor} may hold strong references to more source
73 * emissions than specified.
74 * <p>
75 * When this {@code ReplayProcessor} is terminated via {@link #onError(Throwable)} or {@link #onComplete()},
76 * late {@link Subscriber}s will receive the retained/cached items first (if any) followed by the respective
77 * terminal event. If the {@code ReplayProcessor} has a time-bound, the age of the retained/cached items are still considered
78 * when replaying and thus it may result in no items being emitted before the terminal event.
79 * <p>
80 * Once an {@code Subscriber} has subscribed, it will receive items continuously from that point on. Bounds only affect how
81 * many past items a new {@code Subscriber} will receive before it catches up with the live event feed.
82 * <p>
83 * Even though {@code ReplayProcessor} implements the {@code Subscriber} interface, calling
84 * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>)
85 * if the processor is used as a standalone source. However, calling {@code onSubscribe}
86 * after the {@code ReplayProcessor} reached its terminal state will result in the
87 * given {@code Subscription} being canceled immediately.
88 * <p>
89 * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()}
90 * is required to be serialized (called from the same thread or called non-overlappingly from different threads
91 * through external means of serialization). The {@link #toSerialized()} method available to all {@code FlowableProcessor}s
92 * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber}
93 * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively).
94 * <p>
95 * This {@code ReplayProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()},
96 * {@link #getThrowable()} and {@link #hasSubscribers()} as well as means to read the retained/cached items
97 * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()},
98 * {@link #getValues()} or {@link #getValues(Object[])}.
99 * <p>
100 * Note that due to concurrency requirements, a size- and time-bounded {@code ReplayProcessor} may hold strong references to more
101 * source emissions than specified while it isn't terminated yet. Use the {@link #cleanupBuffer()} to allow
102 * such inaccessible items to be cleaned up by GC once no consumer references them anymore.
103 * <dl>
104 * <dt><b>Backpressure:</b></dt>
105 * <dd>This {@code ReplayProcessor} respects the individual backpressure behavior of its {@code Subscriber}s but
106 * does not coordinate their request amounts towards the upstream (because there might not be any) and
107 * consumes the upstream in an unbounded manner (requesting {@link Long#MAX_VALUE}).
108 * Note that {@code Subscriber}s receive a continuous sequence of values after they subscribed even
109 * if an individual item gets delayed due to backpressure.</dd>
110 * <dt><b>Scheduler:</b></dt>
111 * <dd>{@code ReplayProcessor} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and
112 * the {@code Subscriber}s get notified on the thread the respective {@code onXXX} methods were invoked.
113 * Time-bound {@code ReplayProcessor}s use the given {@code Scheduler} in their {@code create} methods
114 * as time source to timestamp of items received for the age checks.</dd>
115 * <dt><b>Error handling:</b></dt>
116 * <dd>When the {@link #onError(Throwable)} is called, the {@code ReplayProcessor} 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 ReplayProcessor} 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 ReplayProcessor<Object> processor = new ReplayProcessor<T>();
131 processor.onNext("one");
132 processor.onNext("two");
133 processor.onNext("three");
134 processor.onComplete();
135
136 // both of the following will get the onNext/onComplete calls from above
137 processor.subscribe(subscriber1);
138 processor.subscribe(subscriber2);
139
140 } </pre>
141 *
142 * @param <T> the value type
143 */
144 public final class ReplayProcessor<@NonNull T> extends FlowableProcessor<T> {
145 /** An empty array to avoid allocation in getValues(). */
146 private static final Object[] EMPTY_ARRAY = new Object[0];
147
148 final ReplayBuffer<T> buffer;
149
150 boolean done;
151
152 final AtomicReference<ReplaySubscription<T>[]> subscribers;
153
154 @SuppressWarnings("rawtypes")
155 static final ReplaySubscription[] EMPTY = new ReplaySubscription[0];
156
157 @SuppressWarnings("rawtypes")
158 static final ReplaySubscription[] TERMINATED = new ReplaySubscription[0];
159
160 /**
161 * Creates an unbounded ReplayProcessor.
162 * <p>
163 * The internal buffer is backed by an {@link ArrayList} and starts with an initial capacity of 16. Once the
164 * number of items reaches this capacity, it will grow as necessary (usually by 50%). However, as the
165 * number of items grows, this causes frequent array reallocation and copying, and may hurt performance
166 * and latency. This can be avoided with the {@link #create(int)} overload which takes an initial capacity
167 * parameter and can be tuned to reduce the array reallocation frequency as needed.
168 *
169 * @param <T>
170 * the type of items observed and emitted by the ReplayProcessor
171 * @return the created ReplayProcessor
172 */
173 @CheckReturnValue
174 @NonNull
175 public static <T> ReplayProcessor<T> create() {
176 return new ReplayProcessor<>(new UnboundedReplayBuffer<>(16));
177 }
178
179 /**
180 * Creates an unbounded ReplayProcessor with the specified initial buffer capacity.
181 * <p>
182 * Use this method to avoid excessive array reallocation while the internal buffer grows to accommodate new
183 * items. For example, if you know that the buffer will hold 32k items, you can ask the
184 * {@code ReplayProcessor} to preallocate its internal array with a capacity to hold that many items. Once
185 * the items start to arrive, the internal array won't need to grow, creating less garbage and no overhead
186 * due to frequent array-copying.
187 *
188 * @param <T>
189 * the type of items observed and emitted by this type of processor
190 * @param capacityHint
191 * the initial buffer capacity
192 * @return the created processor
193 * @throws IllegalArgumentException if {@code capacityHint} is non-positive
194 */
195 @CheckReturnValue
196 @NonNull
197 public static <T> ReplayProcessor<T> create(int capacityHint) {
198 ObjectHelper.verifyPositive(capacityHint, "capacityHint");
199 return new ReplayProcessor<>(new UnboundedReplayBuffer<>(capacityHint));
200 }
201
202 /**
203 * Creates a size-bounded ReplayProcessor.
204 * <p>
205 * In this setting, the {@code ReplayProcessor} holds at most {@code size} items in its internal buffer and
206 * discards the oldest item.
207 * <p>
208 * When {@code Subscriber}s subscribe to a terminated {@code ReplayProcessor}, they are guaranteed to see at most
209 * {@code size} {@code onNext} events followed by a termination event.
210 * <p>
211 * If a {@code Subscriber} subscribes while the {@code ReplayProcessor} is active, it will observe all items in the
212 * buffer at that point in time and each item observed afterwards, even if the buffer evicts items due to
213 * the size constraint in the mean time. In other words, once a {@code Subscriber} subscribes, it will receive items
214 * without gaps in the sequence.
215 *
216 * @param <T>
217 * the type of items observed and emitted by this type of processor
218 * @param maxSize
219 * the maximum number of buffered items
220 * @return the created processor
221 * @throws IllegalArgumentException if {@code maxSize} is non-positive
222 */
223 @CheckReturnValue
224 @NonNull
225 public static <T> ReplayProcessor<T> createWithSize(int maxSize) {
226 ObjectHelper.verifyPositive(maxSize, "maxSize");
227 return new ReplayProcessor<>(new SizeBoundReplayBuffer<>(maxSize));
228 }
229
230 /**
231 * Creates an unbounded ReplayProcessor with the bounded-implementation for testing purposes.
232 * <p>
233 * This variant behaves like the regular unbounded {@code ReplayProcessor} created via {@link #create()} but
234 * uses the structures of the bounded-implementation. This is by no means intended for the replacement of
235 * the original, array-backed and unbounded {@code ReplayProcessor} due to the additional overhead of the
236 * linked-list based internal buffer. The sole purpose is to allow testing and reasoning about the behavior
237 * of the bounded implementations without the interference of the eviction policies.
238 *
239 * @param <T>
240 * the type of items observed and emitted by this type of processor
241 * @return the created processor
242 */
243 @CheckReturnValue
244 /* test */ static <T> ReplayProcessor<T> createUnbounded() {
245 return new ReplayProcessor<>(new SizeBoundReplayBuffer<>(Integer.MAX_VALUE));
246 }
247
248 /**
249 * Creates a time-bounded ReplayProcessor.
250 * <p>
251 * In this setting, the {@code ReplayProcessor} internally tags each observed item with a timestamp value
252 * supplied by the {@link Scheduler} and keeps only those whose age is less than the supplied time value
253 * converted to milliseconds. For example, an item arrives at T=0 and the max age is set to 5; at T&gt;=5
254 * this first item is then evicted by any subsequent item or termination event, leaving the buffer empty.
255 * <p>
256 * Once the processor is terminated, {@code Subscriber}s subscribing to it will receive items that remained in the
257 * buffer after the terminal event, regardless of their age.
258 * <p>
259 * If a {@code Subscriber} subscribes while the {@code ReplayProcessor} is active, it will observe only those items
260 * from within the buffer that have an age less than the specified time, and each item observed thereafter,
261 * even if the buffer evicts items due to the time constraint in the mean time. In other words, once a
262 * {@code Subscriber} subscribes, it observes items without gaps in the sequence except for any outdated items at the
263 * beginning of the sequence.
264 * <p>
265 * Note that terminal notifications ({@code onError} and {@code onComplete}) trigger eviction as well. For
266 * example, with a max age of 5, the first item is observed at T=0, then an {@code onComplete} notification
267 * arrives at T=10. If a {@code Subscriber} subscribes at T=11, it will find an empty {@code ReplayProcessor} with just
268 * an {@code onComplete} notification.
269 *
270 * @param <T>
271 * the type of items observed and emitted by this type of processor
272 * @param maxAge
273 * the maximum age of the contained items
274 * @param unit
275 * the time unit of {@code time}
276 * @param scheduler
277 * the {@link Scheduler} that provides the current time
278 * @return the created processor
279 * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null}
280 * @throws IllegalArgumentException if {@code maxAge} is non-positive
281 */
282 @CheckReturnValue
283 @NonNull
284 public static <T> ReplayProcessor<T> createWithTime(long maxAge, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) {
285 ObjectHelper.verifyPositive(maxAge, "maxAge");
286 Objects.requireNonNull(unit, "unit is null");
287 Objects.requireNonNull(scheduler, "scheduler is null");
288 return new ReplayProcessor<>(new SizeAndTimeBoundReplayBuffer<>(Integer.MAX_VALUE, maxAge, unit, scheduler));
289 }
290
291 /**
292 * Creates a time- and size-bounded ReplayProcessor.
293 * <p>
294 * In this setting, the {@code ReplayProcessor} internally tags each received item with a timestamp value
295 * supplied by the {@link Scheduler} and holds at most {@code size} items in its internal buffer. It evicts
296 * items from the start of the buffer if their age becomes less-than or equal to the supplied age in
297 * milliseconds or the buffer reaches its {@code size} limit.
298 * <p>
299 * When {@code Subscriber}s subscribe to a terminated {@code ReplayProcessor}, they observe the items that remained in
300 * the buffer after the terminal notification, regardless of their age, but at most {@code size} items.
301 * <p>
302 * If a {@code Subscriber} subscribes while the {@code ReplayProcessor} is active, it will observe only those items
303 * from within the buffer that have age less than the specified time and each subsequent item, even if the
304 * buffer evicts items due to the time constraint in the mean time. In other words, once a {@code Subscriber}
305 * subscribes, it observes items without gaps in the sequence except for the outdated items at the beginning
306 * of the sequence.
307 * <p>
308 * Note that terminal notifications ({@code onError} and {@code onComplete}) trigger eviction as well. For
309 * example, with a max age of 5, the first item is observed at T=0, then an {@code onComplete} notification
310 * arrives at T=10. If a {@code Subscriber} subscribes at T=11, it will find an empty {@code ReplayProcessor} with just
311 * an {@code onComplete} notification.
312 *
313 * @param <T>
314 * the type of items observed and emitted by this type of processor
315 * @param maxAge
316 * the maximum age of the contained items
317 * @param unit
318 * the time unit of {@code time}
319 * @param maxSize
320 * the maximum number of buffered items
321 * @param scheduler
322 * the {@link Scheduler} that provides the current time
323 * @return the created processor
324 * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null}
325 * @throws IllegalArgumentException if {@code maxAge} or {@code maxSize} is non-positive
326 */
327 @CheckReturnValue
328 @NonNull
329 public static <T> ReplayProcessor<T> createWithTimeAndSize(long maxAge, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, int maxSize) {
330 ObjectHelper.verifyPositive(maxSize, "maxSize");
331 ObjectHelper.verifyPositive(maxAge, "maxAge");
332 Objects.requireNonNull(unit, "unit is null");
333 Objects.requireNonNull(scheduler, "scheduler is null");
334 return new ReplayProcessor<>(new SizeAndTimeBoundReplayBuffer<>(maxSize, maxAge, unit, scheduler));
335 }
336
337 /**
338 * Constructs a ReplayProcessor with the given custom ReplayBuffer instance.
339 * @param buffer the ReplayBuffer instance, not null (not verified)
340 */
341 @SuppressWarnings("unchecked")
342 ReplayProcessor(ReplayBuffer<T> buffer) {
343 this.buffer = buffer;
344 this.subscribers = new AtomicReference<>(EMPTY);
345 }
346
347 @Override
348 protected void subscribeActual(Subscriber<? super T> s) {
349 ReplaySubscription<T> rs = new ReplaySubscription<>(s, this);
350 s.onSubscribe(rs);
351
352 if (add(rs)) {
353 if (rs.cancelled) {
354 remove(rs);
355 return;
356 }
357 }
358 buffer.replay(rs);
359 }
360
361 @Override
362 public void onSubscribe(Subscription s) {
363 if (done) {
364 s.cancel();
365 return;
366 }
367 s.request(Long.MAX_VALUE);
368 }
369
370 @Override
371 public void onNext(T t) {
372 ExceptionHelper.nullCheck(t, "onNext called with a null value.");
373
374 if (done) {
375 return;
376 }
377
378 ReplayBuffer<T> b = buffer;
379 b.next(t);
380
381 for (ReplaySubscription<T> rs : subscribers.get()) {
382 b.replay(rs);
383 }
384 }
385
386 @SuppressWarnings("unchecked")
387 @Override
388 public void onError(Throwable t) {
389 ExceptionHelper.nullCheck(t, "onError called with a null Throwable.");
390
391 if (done) {
392 RxJavaPlugins.onError(t);
393 return;
394 }
395 done = true;
396
397 ReplayBuffer<T> b = buffer;
398 b.error(t);
399
400 for (ReplaySubscription<T> rs : subscribers.getAndSet(TERMINATED)) {
401 b.replay(rs);
402 }
403 }
404
405 @SuppressWarnings("unchecked")
406 @Override
407 public void onComplete() {
408 if (done) {
409 return;
410 }
411 done = true;
412
413 ReplayBuffer<T> b = buffer;
414
415 b.complete();
416
417 for (ReplaySubscription<T> rs : subscribers.getAndSet(TERMINATED)) {
418 b.replay(rs);
419 }
420 }
421
422 @Override
423 @CheckReturnValue
424 public boolean hasSubscribers() {
425 return subscribers.get().length != 0;
426 }
427
428 @CheckReturnValue
429 /* test */ int subscriberCount() {
430 return subscribers.get().length;
431 }
432
433 @Override
434 @Nullable
435 @CheckReturnValue
436 public Throwable getThrowable() {
437 ReplayBuffer<T> b = buffer;
438 if (b.isDone()) {
439 return b.getError();
440 }
441 return null;
442 }
443
444 /**
445 * Makes sure the item cached by the head node in a bounded
446 * ReplayProcessor is released (as it is never part of a replay).
447 * <p>
448 * By default, live bounded buffers will remember one item before
449 * the currently receivable one to ensure subscribers can always
450 * receive a continuous sequence of items. A terminated ReplayProcessor
451 * automatically releases this inaccessible item.
452 * <p>
453 * The method must be called sequentially, similar to the standard
454 * {@code onXXX} methods.
455 * <p>History: 2.1.11 - experimental
456 * @since 2.2
457 */
458 public void cleanupBuffer() {
459 buffer.trimHead();
460 }
461
462 /**
463 * Returns the latest value this processor has or null if no such value exists.
464 * <p>The method is thread-safe.
465 * @return the latest value this processor currently has or null if no such value exists
466 */
467 @CheckReturnValue
468 public T getValue() {
469 return buffer.getValue();
470 }
471
472 /**
473 * Returns an Object array containing snapshot all values of this processor.
474 * <p>The method is thread-safe.
475 * @return the array containing the snapshot of all values of this processor
476 */
477 @CheckReturnValue
478 public Object[] getValues() {
479 @SuppressWarnings("unchecked")
480 T[] a = (T[])EMPTY_ARRAY;
481 T[] b = getValues(a);
482 if (b == EMPTY_ARRAY) {
483 return new Object[0];
484 }
485 return b;
486
487 }
488
489 /**
490 * Returns a typed array containing a snapshot of all values of this processor.
491 * <p>The method follows the conventions of Collection.toArray by setting the array element
492 * after the last value to null (if the capacity permits).
493 * <p>The method is thread-safe.
494 * @param array the target array to copy values into if it fits
495 * @return the given array if the values fit into it or a new array containing all values
496 */
497 @CheckReturnValue
498 public T[] getValues(T[] array) {
499 return buffer.getValues(array);
500 }
501
502 @Override
503 @CheckReturnValue
504 public boolean hasComplete() {
505 ReplayBuffer<T> b = buffer;
506 return b.isDone() && b.getError() == null;
507 }
508
509 @Override
510 @CheckReturnValue
511 public boolean hasThrowable() {
512 ReplayBuffer<T> b = buffer;
513 return b.isDone() && b.getError() != null;
514 }
515
516 /**
517 * Returns true if this processor has any value.
518 * <p>The method is thread-safe.
519 * @return true if the processor has any value
520 */
521 @CheckReturnValue
522 public boolean hasValue() {
523 return buffer.size() != 0; // NOPMD
524 }
525
526 @CheckReturnValue
527 /* test*/ int size() {
528 return buffer.size();
529 }
530
531 boolean add(ReplaySubscription<T> rs) {
532 for (;;) {
533 ReplaySubscription<T>[] a = subscribers.get();
534 if (a == TERMINATED) {
535 return false;
536 }
537 int len = a.length;
538 @SuppressWarnings("unchecked")
539 ReplaySubscription<T>[] b = new ReplaySubscription[len + 1];
540 System.arraycopy(a, 0, b, 0, len);
541 b[len] = rs;
542 if (subscribers.compareAndSet(a, b)) {
543 return true;
544 }
545 }
546 }
547
548 @SuppressWarnings("unchecked")
549 void remove(ReplaySubscription<T> rs) {
550 for (;;) {
551 ReplaySubscription<T>[] a = subscribers.get();
552 if (a == TERMINATED || a == EMPTY) {
553 return;
554 }
555 int len = a.length;
556 int j = -1;
557 for (int i = 0; i < len; i++) {
558 if (a[i] == rs) {
559 j = i;
560 break;
561 }
562 }
563
564 if (j < 0) {
565 return;
566 }
567 ReplaySubscription<T>[] b;
568 if (len == 1) {
569 b = EMPTY;
570 } else {
571 b = new ReplaySubscription[len - 1];
572 System.arraycopy(a, 0, b, 0, j);
573 System.arraycopy(a, j + 1, b, j, len - j - 1);
574 }
575 if (subscribers.compareAndSet(a, b)) {
576 return;
577 }
578 }
579 }
580
581 /**
582 * Abstraction over a buffer that receives events and replays them to
583 * individual Subscribers.
584 *
585 * @param <T> the value type
586 */
587 interface ReplayBuffer<@NonNull T> {
588
589 void next(T value);
590
591 void error(Throwable ex);
592
593 void complete();
594
595 void replay(ReplaySubscription<T> rs);
596
597 int size();
598
599 @Nullable
600 T getValue();
601
602 T[] getValues(T[] array);
603
604 boolean isDone();
605
606 Throwable getError();
607
608 /**
609 * Make sure an old inaccessible head value is released
610 * in a bounded buffer.
611 */
612 void trimHead();
613 }
614
615 static final class ReplaySubscription<@NonNull T> extends AtomicInteger implements Subscription {
616
617 private static final long serialVersionUID = 466549804534799122L;
618 final Subscriber<? super T> downstream;
619 final ReplayProcessor<T> state;
620
621 Object index;
622
623 final AtomicLong requested;
624
625 volatile boolean cancelled;
626
627 long emitted;
628
629 ReplaySubscription(Subscriber<? super T> actual, ReplayProcessor<T> state) {
630 this.downstream = actual;
631 this.state = state;
632 this.requested = new AtomicLong();
633 }
634
635 @Override
636 public void request(long n) {
637 if (SubscriptionHelper.validate(n)) {
638 BackpressureHelper.add(requested, n);
639 state.buffer.replay(this);
640 }
641 }
642
643 @Override
644 public void cancel() {
645 if (!cancelled) {
646 cancelled = true;
647 state.remove(this);
648 }
649 }
650 }
651
652 static final class UnboundedReplayBuffer<T>
653 implements ReplayBuffer<T> {
654
655 final List<T> buffer;
656
657 Throwable error;
658 volatile boolean done;
659
660 volatile int size;
661
662 UnboundedReplayBuffer(int capacityHint) {
663 this.buffer = new ArrayList<>(capacityHint);
664 }
665
666 @Override
667 public void next(T value) {
668 buffer.add(value);
669 size++;
670 }
671
672 @Override
673 public void error(Throwable ex) {
674 error = ex;
675 done = true;
676 }
677
678 @Override
679 public void complete() {
680 done = true;
681 }
682
683 @Override
684 public void trimHead() {
685 // not applicable for an unbounded buffer
686 }
687
688 @Override
689 @Nullable
690 public T getValue() {
691 int s = size;
692 if (s == 0) {
693 return null;
694 }
695 return buffer.get(s - 1);
696 }
697
698 @Override
699 @SuppressWarnings("unchecked")
700 public T[] getValues(T[] array) {
701 int s = size;
702 if (s == 0) {
703 if (array.length != 0) {
704 array[0] = null;
705 }
706 return array;
707 }
708 List<T> b = buffer;
709
710 if (array.length < s) {
711 array = (T[])Array.newInstance(array.getClass().getComponentType(), s);
712 }
713 for (int i = 0; i < s; i++) {
714 array[i] = b.get(i);
715 }
716 if (array.length > s) {
717 array[s] = null;
718 }
719
720 return array;
721 }
722
723 @Override
724 public void replay(ReplaySubscription<T> rs) {
725 if (rs.getAndIncrement() != 0) {
726 return;
727 }
728
729 int missed = 1;
730 final List<T> b = buffer;
731 final Subscriber<? super T> a = rs.downstream;
732
733 Integer indexObject = (Integer)rs.index;
734 int index;
735 if (indexObject != null) {
736 index = indexObject;
737 } else {
738 index = 0;
739 rs.index = 0;
740 }
741 long e = rs.emitted;
742
743 for (;;) {
744
745 long r = rs.requested.get();
746
747 while (e != r) {
748 if (rs.cancelled) {
749 rs.index = null;
750 return;
751 }
752
753 boolean d = done;
754 int s = size;
755
756 if (d && index == s) {
757 rs.index = null;
758 rs.cancelled = true;
759 Throwable ex = error;
760 if (ex == null) {
761 a.onComplete();
762 } else {
763 a.onError(ex);
764 }
765 return;
766 }
767
768 if (index == s) {
769 break;
770 }
771
772 a.onNext(b.get(index));
773
774 index++;
775 e++;
776 }
777
778 if (e == r) {
779 if (rs.cancelled) {
780 rs.index = null;
781 return;
782 }
783
784 boolean d = done;
785 int s = size;
786
787 if (d && index == s) {
788 rs.index = null;
789 rs.cancelled = true;
790 Throwable ex = error;
791 if (ex == null) {
792 a.onComplete();
793 } else {
794 a.onError(ex);
795 }
796 return;
797 }
798 }
799
800 rs.index = index;
801 rs.emitted = e;
802 missed = rs.addAndGet(-missed);
803 if (missed == 0) {
804 break;
805 }
806 }
807 }
808
809 @Override
810 public int size() {
811 return size;
812 }
813
814 @Override
815 public boolean isDone() {
816 return done;
817 }
818
819 @Override
820 public Throwable getError() {
821 return error;
822 }
823 }
824
825 static final class Node<T> extends AtomicReference<Node<T>> {
826
827 private static final long serialVersionUID = 6404226426336033100L;
828
829 final T value;
830
831 Node(T value) {
832 this.value = value;
833 }
834 }
835
836 static final class TimedNode<T> extends AtomicReference<TimedNode<T>> {
837
838 private static final long serialVersionUID = 6404226426336033100L;
839
840 final T value;
841 final long time;
842
843 TimedNode(T value, long time) {
844 this.value = value;
845 this.time = time;
846 }
847 }
848
849 static final class SizeBoundReplayBuffer<@NonNull T>
850 implements ReplayBuffer<T> {
851
852 final int maxSize;
853 int size;
854
855 volatile Node<T> head;
856
857 Node<T> tail;
858
859 Throwable error;
860 volatile boolean done;
861
862 SizeBoundReplayBuffer(int maxSize) {
863 this.maxSize = maxSize;
864 Node<T> h = new Node<>(null);
865 this.tail = h;
866 this.head = h;
867 }
868
869 void trim() {
870 if (size > maxSize) {
871 size--;
872 Node<T> h = head;
873 head = h.get();
874 }
875 }
876
877 @Override
878 public void next(T value) {
879 Node<T> n = new Node<>(value);
880 Node<T> t = tail;
881
882 tail = n;
883 size++;
884 t.set(n); // releases both the tail and size
885
886 trim();
887 }
888
889 @Override
890 public void error(Throwable ex) {
891 error = ex;
892 trimHead();
893 done = true;
894 }
895
896 @Override
897 public void complete() {
898 trimHead();
899 done = true;
900 }
901
902 @Override
903 public void trimHead() {
904 if (head.value != null) {
905 Node<T> n = new Node<>(null);
906 n.lazySet(head.get());
907 head = n;
908 }
909 }
910
911 @Override
912 public boolean isDone() {
913 return done;
914 }
915
916 @Override
917 public Throwable getError() {
918 return error;
919 }
920
921 @Override
922 public T getValue() {
923 Node<T> h = head;
924 for (;;) {
925 Node<T> n = h.get();
926 if (n == null) {
927 return h.value;
928 }
929 h = n;
930 }
931 }
932
933 @Override
934 @SuppressWarnings("unchecked")
935 public T[] getValues(T[] array) {
936 int s = 0;
937 Node<T> h = head;
938 Node<T> h0 = h;
939 for (;;) {
940 Node<T> next = h0.get();
941 if (next == null) {
942 break;
943 }
944 s++;
945 h0 = next;
946 }
947 if (array.length < s) {
948 array = (T[])Array.newInstance(array.getClass().getComponentType(), s);
949 }
950
951 for (int j = 0; j < s; j++) {
952 h = h.get();
953 array[j] = h.value;
954 }
955
956 if (array.length > s) {
957 array[s] = null;
958 }
959 return array;
960 }
961
962 @Override
963 @SuppressWarnings("unchecked")
964 public void replay(ReplaySubscription<T> rs) {
965 if (rs.getAndIncrement() != 0) {
966 return;
967 }
968
969 int missed = 1;
970 final Subscriber<? super T> a = rs.downstream;
971
972 Node<T> index = (Node<T>)rs.index;
973 if (index == null) {
974 index = head;
975 }
976
977 long e = rs.emitted;
978
979 for (;;) {
980
981 long r = rs.requested.get();
982
983 while (e != r) {
984 if (rs.cancelled) {
985 rs.index = null;
986 return;
987 }
988
989 boolean d = done;
990 Node<T> next = index.get();
991 boolean empty = next == null;
992
993 if (d && empty) {
994 rs.index = null;
995 rs.cancelled = true;
996 Throwable ex = error;
997 if (ex == null) {
998 a.onComplete();
999 } else {
1000 a.onError(ex);
1001 }
1002 return;
1003 }
1004
1005 if (empty) {
1006 break;
1007 }
1008
1009 a.onNext(next.value);
1010 e++;
1011 index = next;
1012 }
1013
1014 if (e == r) {
1015 if (rs.cancelled) {
1016 rs.index = null;
1017 return;
1018 }
1019
1020 boolean d = done;
1021
1022 if (d && index.get() == null) {
1023 rs.index = null;
1024 rs.cancelled = true;
1025 Throwable ex = error;
1026 if (ex == null) {
1027 a.onComplete();
1028 } else {
1029 a.onError(ex);
1030 }
1031 return;
1032 }
1033 }
1034
1035 rs.index = index;
1036 rs.emitted = e;
1037
1038 missed = rs.addAndGet(-missed);
1039 if (missed == 0) {
1040 break;
1041 }
1042 }
1043 }
1044
1045 @Override
1046 public int size() {
1047 int s = 0;
1048 Node<T> h = head;
1049 while (s != Integer.MAX_VALUE) {
1050 Node<T> next = h.get();
1051 if (next == null) {
1052 break;
1053 }
1054 s++;
1055 h = next;
1056 }
1057
1058 return s;
1059 }
1060 }
1061
1062 static final class SizeAndTimeBoundReplayBuffer<T>
1063 implements ReplayBuffer<T> {
1064
1065 final int maxSize;
1066 final long maxAge;
1067 final TimeUnit unit;
1068 final Scheduler scheduler;
1069 int size;
1070
1071 volatile TimedNode<T> head;
1072
1073 TimedNode<T> tail;
1074
1075 Throwable error;
1076 volatile boolean done;
1077
1078 SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) {
1079 this.maxSize = maxSize;
1080 this.maxAge = maxAge;
1081 this.unit = unit;
1082 this.scheduler = scheduler;
1083 TimedNode<T> h = new TimedNode<>(null, 0L);
1084 this.tail = h;
1085 this.head = h;
1086 }
1087
1088 void trim() {
1089 if (size > maxSize) {
1090 size--;
1091 TimedNode<T> h = head;
1092 head = h.get();
1093 }
1094 long limit = scheduler.now(unit) - maxAge;
1095
1096 TimedNode<T> h = head;
1097
1098 for (;;) {
1099 if (size <= 1) {
1100 head = h;
1101 break;
1102 }
1103 TimedNode<T> next = h.get();
1104
1105 if (next.time > limit) {
1106 head = h;
1107 break;
1108 }
1109
1110 h = next;
1111 size--;
1112 }
1113
1114 }
1115
1116 void trimFinal() {
1117 long limit = scheduler.now(unit) - maxAge;
1118
1119 TimedNode<T> h = head;
1120
1121 for (;;) {
1122 TimedNode<T> next = h.get();
1123 if (next == null) {
1124 if (h.value != null) {
1125 head = new TimedNode<>(null, 0L);
1126 } else {
1127 head = h;
1128 }
1129 break;
1130 }
1131
1132 if (next.time > limit) {
1133 if (h.value != null) {
1134 TimedNode<T> n = new TimedNode<>(null, 0L);
1135 n.lazySet(h.get());
1136 head = n;
1137 } else {
1138 head = h;
1139 }
1140 break;
1141 }
1142
1143 h = next;
1144 }
1145 }
1146
1147 @Override
1148 public void trimHead() {
1149 if (head.value != null) {
1150 TimedNode<T> n = new TimedNode<>(null, 0L);
1151 n.lazySet(head.get());
1152 head = n;
1153 }
1154 }
1155
1156 @Override
1157 public void next(T value) {
1158 TimedNode<T> n = new TimedNode<>(value, scheduler.now(unit));
1159 TimedNode<T> t = tail;
1160
1161 tail = n;
1162 size++;
1163 t.set(n); // releases both the tail and size
1164
1165 trim();
1166 }
1167
1168 @Override
1169 public void error(Throwable ex) {
1170 trimFinal();
1171 error = ex;
1172 done = true;
1173 }
1174
1175 @Override
1176 public void complete() {
1177 trimFinal();
1178 done = true;
1179 }
1180
1181 @Override
1182 @Nullable
1183 public T getValue() {
1184 TimedNode<T> h = head;
1185
1186 for (;;) {
1187 TimedNode<T> next = h.get();
1188 if (next == null) {
1189 break;
1190 }
1191 h = next;
1192 }
1193
1194 long limit = scheduler.now(unit) - maxAge;
1195 if (h.time < limit) {
1196 return null;
1197 }
1198
1199 return h.value;
1200 }
1201
1202 @Override
1203 @SuppressWarnings("unchecked")
1204 public T[] getValues(T[] array) {
1205 TimedNode<T> h = getHead();
1206 int s = size(h);
1207
1208 if (s == 0) {
1209 if (array.length != 0) {
1210 array[0] = null;
1211 }
1212 } else {
1213 if (array.length < s) {
1214 array = (T[])Array.newInstance(array.getClass().getComponentType(), s);
1215 }
1216
1217 int i = 0;
1218 while (i != s) {
1219 TimedNode<T> next = h.get();
1220 array[i] = next.value;
1221 i++;
1222 h = next;
1223 }
1224 if (array.length > s) {
1225 array[s] = null;
1226 }
1227 }
1228
1229 return array;
1230 }
1231
1232 TimedNode<T> getHead() {
1233 TimedNode<T> index = head;
1234 // skip old entries
1235 long limit = scheduler.now(unit) - maxAge;
1236 TimedNode<T> next = index.get();
1237 while (next != null) {
1238 long ts = next.time;
1239 if (ts > limit) {
1240 break;
1241 }
1242 index = next;
1243 next = index.get();
1244 }
1245 return index;
1246 }
1247
1248 @Override
1249 @SuppressWarnings("unchecked")
1250 public void replay(ReplaySubscription<T> rs) {
1251 if (rs.getAndIncrement() != 0) {
1252 return;
1253 }
1254
1255 int missed = 1;
1256 final Subscriber<? super T> a = rs.downstream;
1257
1258 TimedNode<T> index = (TimedNode<T>)rs.index;
1259 if (index == null) {
1260 index = getHead();
1261 }
1262
1263 long e = rs.emitted;
1264
1265 for (;;) {
1266
1267 long r = rs.requested.get();
1268
1269 while (e != r) {
1270 if (rs.cancelled) {
1271 rs.index = null;
1272 return;
1273 }
1274
1275 boolean d = done;
1276 TimedNode<T> next = index.get();
1277 boolean empty = next == null;
1278
1279 if (d && empty) {
1280 rs.index = null;
1281 rs.cancelled = true;
1282 Throwable ex = error;
1283 if (ex == null) {
1284 a.onComplete();
1285 } else {
1286 a.onError(ex);
1287 }
1288 return;
1289 }
1290
1291 if (empty) {
1292 break;
1293 }
1294
1295 a.onNext(next.value);
1296 e++;
1297 index = next;
1298 }
1299
1300 if (e == r) {
1301 if (rs.cancelled) {
1302 rs.index = null;
1303 return;
1304 }
1305
1306 boolean d = done;
1307
1308 if (d && index.get() == null) {
1309 rs.index = null;
1310 rs.cancelled = true;
1311 Throwable ex = error;
1312 if (ex == null) {
1313 a.onComplete();
1314 } else {
1315 a.onError(ex);
1316 }
1317 return;
1318 }
1319 }
1320
1321 rs.index = index;
1322 rs.emitted = e;
1323
1324 missed = rs.addAndGet(-missed);
1325 if (missed == 0) {
1326 break;
1327 }
1328 }
1329 }
1330
1331 @Override
1332 public int size() {
1333 return size(getHead());
1334 }
1335
1336 int size(TimedNode<T> h) {
1337 int s = 0;
1338 while (s != Integer.MAX_VALUE) {
1339 TimedNode<T> next = h.get();
1340 if (next == null) {
1341 break;
1342 }
1343 s++;
1344 h = next;
1345 }
1346
1347 return s;
1348 }
1349
1350 @Override
1351 public Throwable getError() {
1352 return error;
1353 }
1354
1355 @Override
1356 public boolean isDone() {
1357 return done;
1358 }
1359 }
1360 }