Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableWindowTimed.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.internal.operators.flowable;
15
16 import java.util.*;
17 import java.util.concurrent.TimeUnit;
18 import java.util.concurrent.atomic.*;
19
20 import org.reactivestreams.*;
21
22 import io.reactivex.rxjava3.core.*;
23 import io.reactivex.rxjava3.core.Scheduler.Worker;
24 import io.reactivex.rxjava3.exceptions.MissingBackpressureException;
25 import io.reactivex.rxjava3.internal.disposables.SequentialDisposable;
26 import io.reactivex.rxjava3.internal.queue.MpscLinkedQueue;
27 import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
28 import io.reactivex.rxjava3.internal.util.BackpressureHelper;
29 import io.reactivex.rxjava3.operators.SimplePlainQueue;
30 import io.reactivex.rxjava3.processors.UnicastProcessor;
31
32 public final class FlowableWindowTimed<T> extends AbstractFlowableWithUpstream<T, Flowable<T>> {
33 final long timespan;
34 final long timeskip;
35 final TimeUnit unit;
36 final Scheduler scheduler;
37 final long maxSize;
38 final int bufferSize;
39 final boolean restartTimerOnMaxSize;
40
41 public FlowableWindowTimed(Flowable<T> source,
42 long timespan, long timeskip, TimeUnit unit, Scheduler scheduler, long maxSize,
43 int bufferSize, boolean restartTimerOnMaxSize) {
44 super(source);
45 this.timespan = timespan;
46 this.timeskip = timeskip;
47 this.unit = unit;
48 this.scheduler = scheduler;
49 this.maxSize = maxSize;
50 this.bufferSize = bufferSize;
51 this.restartTimerOnMaxSize = restartTimerOnMaxSize;
52 }
53
54 @Override
55 protected void subscribeActual(Subscriber<? super Flowable<T>> downstream) {
56 if (timespan == timeskip) {
57 if (maxSize == Long.MAX_VALUE) {
58 source.subscribe(new WindowExactUnboundedSubscriber<>(
59 downstream,
60 timespan, unit, scheduler, bufferSize));
61 return;
62 }
63 source.subscribe(new WindowExactBoundedSubscriber<>(
64 downstream,
65 timespan, unit, scheduler,
66 bufferSize, maxSize, restartTimerOnMaxSize));
67 return;
68 }
69 source.subscribe(new WindowSkipSubscriber<>(downstream,
70 timespan, timeskip, unit, scheduler.createWorker(), bufferSize));
71 }
72
73 abstract static class AbstractWindowSubscriber<T>
74 extends AtomicInteger
75 implements FlowableSubscriber<T>, Subscription {
76 private static final long serialVersionUID = 5724293814035355511L;
77
78 final Subscriber<? super Flowable<T>> downstream;
79
80 final SimplePlainQueue<Object> queue;
81
82 final long timespan;
83 final TimeUnit unit;
84 final int bufferSize;
85
86 final AtomicLong requested;
87 long emitted;
88
89 volatile boolean done;
90 Throwable error;
91
92 Subscription upstream;
93
94 final AtomicBoolean downstreamCancelled;
95
96 volatile boolean upstreamCancelled;
97
98 final AtomicInteger windowCount;
99
100 AbstractWindowSubscriber(Subscriber<? super Flowable<T>> downstream, long timespan, TimeUnit unit, int bufferSize) {
101 this.downstream = downstream;
102 this.queue = new MpscLinkedQueue<>();
103 this.timespan = timespan;
104 this.unit = unit;
105 this.bufferSize = bufferSize;
106 this.requested = new AtomicLong();
107 this.downstreamCancelled = new AtomicBoolean();
108 this.windowCount = new AtomicInteger(1);
109 }
110
111 @Override
112 public final void onSubscribe(Subscription s) {
113 if (SubscriptionHelper.validate(this.upstream, s)) {
114 this.upstream = s;
115
116 downstream.onSubscribe(this);
117
118 createFirstWindow();
119 }
120 }
121
122 abstract void createFirstWindow();
123
124 @Override
125 public final void onNext(T t) {
126 queue.offer(t);
127 drain();
128 }
129
130 @Override
131 public final void onError(Throwable t) {
132 error = t;
133 done = true;
134 drain();
135 }
136
137 @Override
138 public final void onComplete() {
139 done = true;
140 drain();
141 }
142
143 @Override
144 public final void request(long n) {
145 if (SubscriptionHelper.validate(n)) {
146 BackpressureHelper.add(requested, n);
147 }
148 }
149
150 @Override
151 public final void cancel() {
152 if (downstreamCancelled.compareAndSet(false, true)) {
153 windowDone();
154 }
155 }
156
157 final void windowDone() {
158 if (windowCount.decrementAndGet() == 0) {
159 cleanupResources();
160 upstream.cancel();
161 upstreamCancelled = true;
162 drain();
163 }
164 }
165
166 abstract void cleanupResources();
167
168 abstract void drain();
169 }
170
171 static final class WindowExactUnboundedSubscriber<T>
172 extends AbstractWindowSubscriber<T>
173 implements Runnable {
174
175 private static final long serialVersionUID = 1155822639622580836L;
176
177 final Scheduler scheduler;
178
179 UnicastProcessor<T> window;
180
181 final SequentialDisposable timer;
182
183 static final Object NEXT_WINDOW = new Object();
184
185 final Runnable windowRunnable;
186
187 WindowExactUnboundedSubscriber(Subscriber<? super Flowable<T>> actual, long timespan, TimeUnit unit,
188 Scheduler scheduler, int bufferSize) {
189 super(actual, timespan, unit, bufferSize);
190 this.scheduler = scheduler;
191 this.timer = new SequentialDisposable();
192 this.windowRunnable = new WindowRunnable();
193 }
194
195 @Override
196 void createFirstWindow() {
197 if (!downstreamCancelled.get()) {
198 if (requested.get() != 0L) {
199 windowCount.getAndIncrement();
200 window = UnicastProcessor.create(bufferSize, windowRunnable);
201
202 emitted = 1;
203
204 FlowableWindowSubscribeIntercept<T> intercept = new FlowableWindowSubscribeIntercept<>(window);
205 downstream.onNext(intercept);
206
207 timer.replace(scheduler.schedulePeriodicallyDirect(this, timespan, timespan, unit));
208
209 if (intercept.tryAbandon()) {
210 window.onComplete();
211 }
212
213 upstream.request(Long.MAX_VALUE);
214 } else {
215 upstream.cancel();
216 downstream.onError(new MissingBackpressureException(missingBackpressureMessage(emitted)));
217
218 cleanupResources();
219 upstreamCancelled = true;
220 }
221 }
222 }
223
224 @Override
225 public void run() {
226 queue.offer(NEXT_WINDOW);
227 drain();
228 }
229
230 @Override
231 void drain() {
232 if (getAndIncrement() != 0) {
233 return;
234 }
235
236 final SimplePlainQueue<Object> queue = this.queue;
237 final Subscriber<? super Flowable<T>> downstream = this.downstream;
238 UnicastProcessor<T> window = this.window;
239
240 int missed = 1;
241 for (;;) {
242
243 if (upstreamCancelled) {
244 queue.clear();
245 window = null;
246 this.window = null;
247 } else {
248 boolean isDone = done;
249 Object o = queue.poll();
250 boolean isEmpty = o == null;
251
252 if (isDone && isEmpty) {
253 Throwable ex = error;
254 if (ex != null) {
255 if (window != null) {
256 window.onError(ex);
257 }
258 downstream.onError(ex);
259 } else {
260 if (window != null) {
261 window.onComplete();
262 }
263 downstream.onComplete();
264 }
265 cleanupResources();
266 upstreamCancelled = true;
267 continue;
268 }
269 else if (!isEmpty) {
270
271 if (o == NEXT_WINDOW) {
272 if (window != null) {
273 window.onComplete();
274 window = null;
275 this.window = null;
276 }
277 if (downstreamCancelled.get()) {
278 timer.dispose();
279 } else {
280 if (requested.get() == emitted) {
281 upstream.cancel();
282 cleanupResources();
283 upstreamCancelled = true;
284
285 downstream.onError(new MissingBackpressureException(missingBackpressureMessage(emitted)));
286 } else {
287 emitted++;
288
289 windowCount.getAndIncrement();
290 window = UnicastProcessor.create(bufferSize, windowRunnable);
291 this.window = window;
292
293 FlowableWindowSubscribeIntercept<T> intercept = new FlowableWindowSubscribeIntercept<>(window);
294 downstream.onNext(intercept);
295
296 if (intercept.tryAbandon()) {
297 window.onComplete();
298 }
299 }
300 }
301 } else if (window != null) {
302 @SuppressWarnings("unchecked")
303 T item = (T)o;
304 window.onNext(item);
305 }
306
307 continue;
308 }
309 }
310
311 missed = addAndGet(-missed);
312 if (missed == 0) {
313 break;
314 }
315 }
316 }
317
318 @Override
319 void cleanupResources() {
320 timer.dispose();
321 }
322
323 final class WindowRunnable implements Runnable {
324 @Override
325 public void run() {
326 windowDone();
327 }
328 }
329 }
330
331 static final class WindowExactBoundedSubscriber<T>
332 extends AbstractWindowSubscriber<T>
333 implements Runnable {
334 private static final long serialVersionUID = -6130475889925953722L;
335
336 final Scheduler scheduler;
337 final boolean restartTimerOnMaxSize;
338 final long maxSize;
339 final Scheduler.Worker worker;
340
341 long count;
342
343 UnicastProcessor<T> window;
344
345 final SequentialDisposable timer;
346
347 WindowExactBoundedSubscriber(
348 Subscriber<? super Flowable<T>> actual,
349 long timespan, TimeUnit unit, Scheduler scheduler,
350 int bufferSize, long maxSize, boolean restartTimerOnMaxSize) {
351 super(actual, timespan, unit, bufferSize);
352 this.scheduler = scheduler;
353 this.maxSize = maxSize;
354 this.restartTimerOnMaxSize = restartTimerOnMaxSize;
355 if (restartTimerOnMaxSize) {
356 worker = scheduler.createWorker();
357 } else {
358 worker = null;
359 }
360 this.timer = new SequentialDisposable();
361 }
362
363 @Override
364 void createFirstWindow() {
365 if (!downstreamCancelled.get()) {
366 if (requested.get() != 0L) {
367 emitted = 1;
368
369 windowCount.getAndIncrement();
370 window = UnicastProcessor.create(bufferSize, this);
371
372 FlowableWindowSubscribeIntercept<T> intercept = new FlowableWindowSubscribeIntercept<>(window);
373 downstream.onNext(intercept);
374
375 Runnable boundaryTask = new WindowBoundaryRunnable(this, 1L);
376 if (restartTimerOnMaxSize) {
377 timer.replace(worker.schedulePeriodically(boundaryTask, timespan, timespan, unit));
378 } else {
379 timer.replace(scheduler.schedulePeriodicallyDirect(boundaryTask, timespan, timespan, unit));
380 }
381
382 if (intercept.tryAbandon()) {
383 window.onComplete();
384 }
385
386 upstream.request(Long.MAX_VALUE);
387 } else {
388 upstream.cancel();
389 downstream.onError(new MissingBackpressureException(missingBackpressureMessage(emitted)));
390
391 cleanupResources();
392 upstreamCancelled = true;
393 }
394 }
395 }
396
397 @Override
398 public void run() {
399 windowDone();
400 }
401
402 @Override
403 void cleanupResources() {
404 timer.dispose();
405 Worker w = worker;
406 if (w != null) {
407 w.dispose();
408 }
409 }
410
411 void boundary(WindowBoundaryRunnable sender) {
412 queue.offer(sender);
413 drain();
414 }
415
416 @Override
417 void drain() {
418 if (getAndIncrement() != 0) {
419 return;
420 }
421
422 int missed = 1;
423 final SimplePlainQueue<Object> queue = this.queue;
424 final Subscriber<? super Flowable<T>> downstream = this.downstream;
425 UnicastProcessor<T> window = this.window;
426
427 for (;;) {
428
429 if (upstreamCancelled) {
430 queue.clear();
431 window = null;
432 this.window = null;
433 } else {
434
435 boolean isDone = done;
436 Object o = queue.poll();
437 boolean isEmpty = o == null;
438
439 if (isDone && isEmpty) {
440 Throwable ex = error;
441 if (ex != null) {
442 if (window != null) {
443 window.onError(ex);
444 }
445 downstream.onError(ex);
446 } else {
447 if (window != null) {
448 window.onComplete();
449 }
450 downstream.onComplete();
451 }
452 cleanupResources();
453 upstreamCancelled = true;
454 continue;
455 } else if (!isEmpty) {
456 if (o instanceof WindowBoundaryRunnable) {
457 WindowBoundaryRunnable boundary = (WindowBoundaryRunnable) o;
458 if (boundary.index == emitted || !restartTimerOnMaxSize) {
459 this.count = 0;
460 window = createNewWindow(window);
461 }
462 } else if (window != null) {
463 @SuppressWarnings("unchecked")
464 T item = (T)o;
465 window.onNext(item);
466
467 long count = this.count + 1;
468 if (count == maxSize) {
469 this.count = 0;
470 window = createNewWindow(window);
471 } else {
472 this.count = count;
473 }
474 }
475
476 continue;
477 }
478 }
479
480 missed = addAndGet(-missed);
481 if (missed == 0) {
482 break;
483 }
484 }
485 }
486
487 UnicastProcessor<T> createNewWindow(UnicastProcessor<T> window) {
488 if (window != null) {
489 window.onComplete();
490 window = null;
491 }
492
493 if (downstreamCancelled.get()) {
494 cleanupResources();
495 } else {
496 long emitted = this.emitted;
497 if (requested.get() == emitted) {
498 upstream.cancel();
499 cleanupResources();
500 upstreamCancelled = true;
501
502 downstream.onError(new MissingBackpressureException(missingBackpressureMessage(emitted)));
503 } else {
504 this.emitted = ++emitted;
505
506 windowCount.getAndIncrement();
507 window = UnicastProcessor.create(bufferSize, this);
508 this.window = window;
509
510 FlowableWindowSubscribeIntercept<T> intercept = new FlowableWindowSubscribeIntercept<>(window);
511 downstream.onNext(intercept);
512
513 if (restartTimerOnMaxSize) {
514 timer.update(worker.schedulePeriodically(new WindowBoundaryRunnable(this, emitted), timespan, timespan, unit));
515 }
516
517 if (intercept.tryAbandon()) {
518 window.onComplete();
519 }
520 }
521 }
522
523 return window;
524 }
525
526 static final class WindowBoundaryRunnable implements Runnable {
527
528 final WindowExactBoundedSubscriber<?> parent;
529
530 final long index;
531
532 WindowBoundaryRunnable(WindowExactBoundedSubscriber<?> parent, long index) {
533 this.parent = parent;
534 this.index = index;
535 }
536
537 @Override
538 public void run() {
539 parent.boundary(this);
540 }
541 }
542 }
543
544 static final class WindowSkipSubscriber<T>
545 extends AbstractWindowSubscriber<T>
546 implements Runnable {
547 private static final long serialVersionUID = -7852870764194095894L;
548
549 final long timeskip;
550 final Scheduler.Worker worker;
551
552 final List<UnicastProcessor<T>> windows;
553
554 WindowSkipSubscriber(Subscriber<? super Flowable<T>> actual,
555 long timespan, long timeskip, TimeUnit unit,
556 Worker worker, int bufferSize) {
557 super(actual, timespan, unit, bufferSize);
558 this.timeskip = timeskip;
559 this.worker = worker;
560 this.windows = new LinkedList<>();
561 }
562
563 @Override
564 void createFirstWindow() {
565 if (!downstreamCancelled.get()) {
566 if (requested.get() != 0L) {
567 emitted = 1;
568
569 windowCount.getAndIncrement();
570 UnicastProcessor<T> window = UnicastProcessor.create(bufferSize, this);
571 windows.add(window);
572
573 FlowableWindowSubscribeIntercept<T> intercept = new FlowableWindowSubscribeIntercept<>(window);
574 downstream.onNext(intercept);
575
576 worker.schedule(new WindowBoundaryRunnable(this, false), timespan, unit);
577 worker.schedulePeriodically(new WindowBoundaryRunnable(this, true), timeskip, timeskip, unit);
578
579 if (intercept.tryAbandon()) {
580 window.onComplete();
581 windows.remove(window);
582 }
583
584 upstream.request(Long.MAX_VALUE);
585 } else {
586 upstream.cancel();
587 downstream.onError(new MissingBackpressureException(missingBackpressureMessage(emitted)));
588
589 cleanupResources();
590 upstreamCancelled = true;
591 }
592 }
593 }
594
595 @Override
596 void cleanupResources() {
597 worker.dispose();
598 }
599
600 @Override
601 void drain() {
602 if (getAndIncrement() != 0) {
603 return;
604 }
605
606 int missed = 1;
607 final SimplePlainQueue<Object> queue = this.queue;
608 final Subscriber<? super Flowable<T>> downstream = this.downstream;
609 final List<UnicastProcessor<T>> windows = this.windows;
610
611 for (;;) {
612 if (upstreamCancelled) {
613 queue.clear();
614 windows.clear();
615 } else {
616 boolean isDone = done;
617 Object o = queue.poll();
618 boolean isEmpty = o == null;
619
620 if (isDone && isEmpty) {
621 Throwable ex = error;
622 if (ex != null) {
623 for (UnicastProcessor<T> window : windows) {
624 window.onError(ex);
625 }
626 downstream.onError(ex);
627 } else {
628 for (UnicastProcessor<T> window : windows) {
629 window.onComplete();
630 }
631 downstream.onComplete();
632 }
633 cleanupResources();
634 upstreamCancelled = true;
635 continue;
636 } else if (!isEmpty) {
637 if (o == WINDOW_OPEN) {
638 if (!downstreamCancelled.get()) {
639 long emitted = this.emitted;
640 if (requested.get() != emitted) {
641 this.emitted = ++emitted;
642
643 windowCount.getAndIncrement();
644 UnicastProcessor<T> window = UnicastProcessor.create(bufferSize, this);
645 windows.add(window);
646
647 FlowableWindowSubscribeIntercept<T> intercept = new FlowableWindowSubscribeIntercept<>(window);
648 downstream.onNext(intercept);
649
650 worker.schedule(new WindowBoundaryRunnable(this, false), timespan, unit);
651
652 if (intercept.tryAbandon()) {
653 window.onComplete();
654 }
655 } else {
656 upstream.cancel();
657 Throwable ex = new MissingBackpressureException(missingBackpressureMessage(emitted));
658 for (UnicastProcessor<T> window : windows) {
659 window.onError(ex);
660 }
661 downstream.onError(ex);
662
663 cleanupResources();
664 upstreamCancelled = true;
665 continue;
666 }
667 }
668 } else if (o == WINDOW_CLOSE) {
669 if (!windows.isEmpty()) {
670 windows.remove(0).onComplete();
671 }
672 } else {
673 @SuppressWarnings("unchecked")
674 T item = (T)o;
675 for (UnicastProcessor<T> window : windows) {
676 window.onNext(item);
677 }
678 }
679 continue;
680 }
681 }
682 missed = addAndGet(-missed);
683 if (missed == 0) {
684 break;
685 }
686 }
687 }
688
689 @Override
690 public void run() {
691 windowDone();
692 }
693
694 void boundary(boolean isOpen) {
695 queue.offer(isOpen ? WINDOW_OPEN : WINDOW_CLOSE);
696 drain();
697 }
698
699 static final Object WINDOW_OPEN = new Object();
700 static final Object WINDOW_CLOSE = new Object();
701
702 static final class WindowBoundaryRunnable implements Runnable {
703
704 final WindowSkipSubscriber<?> parent;
705
706 final boolean isOpen;
707
708 WindowBoundaryRunnable(WindowSkipSubscriber<?> parent, boolean isOpen) {
709 this.parent = parent;
710 this.isOpen = isOpen;
711 }
712
713 @Override
714 public void run() {
715 parent.boundary(isOpen);
716 }
717 }
718 }
719
720 static String missingBackpressureMessage(long index) {
721 return "Unable to emit the next window (#" + index + ") due to lack of requests. Please make sure the downstream is ready to consume windows.";
722 }
723
724 }