Debian Codegraph @

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