Debian Codegraph @

src/test/java/io/reactivex/rxjava3/schedulers/AbstractSchedulerTests.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.schedulers;
15
16 import static org.junit.Assert.*;
17 import static org.mockito.Mockito.*;
18
19 import java.util.*;
20 import java.util.concurrent.*;
21 import java.util.concurrent.atomic.*;
22
23 import org.junit.Test;
24 import org.mockito.InOrder;
25 import org.mockito.invocation.InvocationOnMock;
26 import org.mockito.stubbing.Answer;
27 import org.reactivestreams.*;
28
29 import io.reactivex.rxjava3.core.*;
30 import io.reactivex.rxjava3.core.Scheduler.Worker;
31 import io.reactivex.rxjava3.disposables.Disposable;
32 import io.reactivex.rxjava3.functions.*;
33 import io.reactivex.rxjava3.internal.disposables.SequentialDisposable;
34 import io.reactivex.rxjava3.internal.functions.Functions;
35 import io.reactivex.rxjava3.internal.schedulers.TrampolineScheduler;
36 import io.reactivex.rxjava3.internal.subscriptions.*;
37 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
38 import io.reactivex.rxjava3.subscribers.DefaultSubscriber;
39
40 /**
41 * Base tests for all schedulers including Immediate/Current.
42 */
43 public abstract class AbstractSchedulerTests extends RxJavaTest {
44
45 /**
46 * The scheduler to test.
47 *
48 * @return the Scheduler instance
49 */
50 protected abstract Scheduler getScheduler();
51
52 @Test
53 public void nestedActions() throws InterruptedException {
54 Scheduler scheduler = getScheduler();
55 final Scheduler.Worker inner = scheduler.createWorker();
56 try {
57 final CountDownLatch latch = new CountDownLatch(1);
58
59 final Runnable firstStepStart = mock(Runnable.class);
60 final Runnable firstStepEnd = mock(Runnable.class);
61
62 final Runnable secondStepStart = mock(Runnable.class);
63 final Runnable secondStepEnd = mock(Runnable.class);
64
65 final Runnable thirdStepStart = mock(Runnable.class);
66 final Runnable thirdStepEnd = mock(Runnable.class);
67
68 final Runnable firstAction = new Runnable() {
69 @Override
70 public void run() {
71 firstStepStart.run();
72 firstStepEnd.run();
73 latch.countDown();
74 }
75 };
76 final Runnable secondAction = new Runnable() {
77 @Override
78 public void run() {
79 secondStepStart.run();
80 inner.schedule(firstAction);
81 secondStepEnd.run();
82
83 }
84 };
85 final Runnable thirdAction = new Runnable() {
86 @Override
87 public void run() {
88 thirdStepStart.run();
89 inner.schedule(secondAction);
90 thirdStepEnd.run();
91 }
92 };
93
94 InOrder inOrder = inOrder(firstStepStart, firstStepEnd, secondStepStart, secondStepEnd, thirdStepStart, thirdStepEnd);
95
96 inner.schedule(thirdAction);
97
98 latch.await();
99
100 inOrder.verify(thirdStepStart, times(1)).run();
101 inOrder.verify(thirdStepEnd, times(1)).run();
102 inOrder.verify(secondStepStart, times(1)).run();
103 inOrder.verify(secondStepEnd, times(1)).run();
104 inOrder.verify(firstStepStart, times(1)).run();
105 inOrder.verify(firstStepEnd, times(1)).run();
106 } finally {
107 inner.dispose();
108 }
109 }
110
111 @Test
112 public final void nestedScheduling() {
113
114 Flowable<Integer> ids = Flowable.fromIterable(Arrays.asList(1, 2)).subscribeOn(getScheduler());
115
116 Flowable<String> m = ids.flatMap(new Function<Integer, Flowable<String>>() {
117
118 @Override
119 public Flowable<String> apply(Integer id) {
120 return Flowable.fromIterable(Arrays.asList("a-" + id, "b-" + id)).subscribeOn(getScheduler())
121 .map(new Function<String, String>() {
122
123 @Override
124 public String apply(String s) {
125 return "names=>" + s;
126 }
127 });
128 }
129
130 });
131
132 List<String> strings = m.toList().blockingGet();
133
134 assertEquals(4, strings.size());
135 // because flatMap does a merge there is no guarantee of order
136 assertTrue(strings.contains("names=>a-1"));
137 assertTrue(strings.contains("names=>a-2"));
138 assertTrue(strings.contains("names=>b-1"));
139 assertTrue(strings.contains("names=>b-2"));
140 }
141
142 /**
143 * The order of execution is nondeterministic.
144 *
145 * @throws InterruptedException if the await is interrupted
146 */
147 @SuppressWarnings("rawtypes")
148 @Test
149 public final void sequenceOfActions() throws InterruptedException {
150 final Scheduler scheduler = getScheduler();
151 final Scheduler.Worker inner = scheduler.createWorker();
152 try {
153 final CountDownLatch latch = new CountDownLatch(2);
154 final Runnable first = mock(Runnable.class);
155 final Runnable second = mock(Runnable.class);
156
157 // make it wait until both the first and second are called
158 doAnswer(new Answer() {
159
160 @Override
161 public Object answer(InvocationOnMock invocation) throws Throwable {
162 try {
163 return invocation.getMock();
164 } finally {
165 latch.countDown();
166 }
167 }
168 }).when(first).run();
169 doAnswer(new Answer() {
170
171 @Override
172 public Object answer(InvocationOnMock invocation) throws Throwable {
173 try {
174 return invocation.getMock();
175 } finally {
176 latch.countDown();
177 }
178 }
179 }).when(second).run();
180
181 inner.schedule(first);
182 inner.schedule(second);
183
184 latch.await();
185
186 verify(first, times(1)).run();
187 verify(second, times(1)).run();
188 } finally {
189 inner.dispose();
190 }
191 }
192
193 @Test
194 public void sequenceOfDelayedActions() throws InterruptedException {
195 Scheduler scheduler = getScheduler();
196 final Scheduler.Worker inner = scheduler.createWorker();
197
198 try {
199 final CountDownLatch latch = new CountDownLatch(1);
200 final Runnable first = mock(Runnable.class);
201 final Runnable second = mock(Runnable.class);
202
203 inner.schedule(new Runnable() {
204 @Override
205 public void run() {
206 inner.schedule(first, 30, TimeUnit.MILLISECONDS);
207 inner.schedule(second, 10, TimeUnit.MILLISECONDS);
208 inner.schedule(new Runnable() {
209
210 @Override
211 public void run() {
212 latch.countDown();
213 }
214 }, 40, TimeUnit.MILLISECONDS);
215 }
216 });
217
218 latch.await();
219 InOrder inOrder = inOrder(first, second);
220
221 inOrder.verify(second, times(1)).run();
222 inOrder.verify(first, times(1)).run();
223 } finally {
224 inner.dispose();
225 }
226 }
227
228 @Test
229 public void mixOfDelayedAndNonDelayedActions() throws InterruptedException {
230 Scheduler scheduler = getScheduler();
231 final Scheduler.Worker inner = scheduler.createWorker();
232
233 try {
234 final CountDownLatch latch = new CountDownLatch(1);
235 final Runnable first = mock(Runnable.class);
236 final Runnable second = mock(Runnable.class);
237 final Runnable third = mock(Runnable.class);
238 final Runnable fourth = mock(Runnable.class);
239
240 inner.schedule(new Runnable() {
241 @Override
242 public void run() {
243 inner.schedule(first);
244 inner.schedule(second, 300, TimeUnit.MILLISECONDS);
245 inner.schedule(third, 100, TimeUnit.MILLISECONDS);
246 inner.schedule(fourth);
247 inner.schedule(new Runnable() {
248
249 @Override
250 public void run() {
251 latch.countDown();
252 }
253 }, 400, TimeUnit.MILLISECONDS);
254 }
255 });
256
257 latch.await();
258 InOrder inOrder = inOrder(first, second, third, fourth);
259
260 inOrder.verify(first, times(1)).run();
261 inOrder.verify(fourth, times(1)).run();
262 inOrder.verify(third, times(1)).run();
263 inOrder.verify(second, times(1)).run();
264 } finally {
265 inner.dispose();
266 }
267 }
268
269 @Test
270 public final void recursiveExecution() throws InterruptedException {
271 final Scheduler scheduler = getScheduler();
272 final Scheduler.Worker inner = scheduler.createWorker();
273
274 try {
275
276 final AtomicInteger i = new AtomicInteger();
277 final CountDownLatch latch = new CountDownLatch(1);
278 inner.schedule(new Runnable() {
279
280 @Override
281 public void run() {
282 if (i.incrementAndGet() < 100) {
283 inner.schedule(this);
284 } else {
285 latch.countDown();
286 }
287 }
288 });
289
290 latch.await();
291 assertEquals(100, i.get());
292 } finally {
293 inner.dispose();
294 }
295 }
296
297 @Test
298 public final void recursiveExecutionWithDelayTime() throws InterruptedException {
299 Scheduler scheduler = getScheduler();
300 final Scheduler.Worker inner = scheduler.createWorker();
301
302 try {
303 final AtomicInteger i = new AtomicInteger();
304 final CountDownLatch latch = new CountDownLatch(1);
305
306 inner.schedule(new Runnable() {
307
308 int state;
309
310 @Override
311 public void run() {
312 i.set(state);
313 if (state++ < 100) {
314 inner.schedule(this, 1, TimeUnit.MILLISECONDS);
315 } else {
316 latch.countDown();
317 }
318 }
319
320 });
321
322 latch.await();
323 assertEquals(100, i.get());
324 } finally {
325 inner.dispose();
326 }
327 }
328
329 @Test
330 public final void recursiveSchedulerInObservable() {
331 Flowable<Integer> obs = Flowable.unsafeCreate(new Publisher<Integer>() {
332 @Override
333 public void subscribe(final Subscriber<? super Integer> subscriber) {
334 final Scheduler.Worker inner = getScheduler().createWorker();
335
336 AsyncSubscription as = new AsyncSubscription();
337 subscriber.onSubscribe(as);
338 as.setResource(inner);
339
340 inner.schedule(new Runnable() {
341 int i;
342
343 @Override
344 public void run() {
345 if (i > 42) {
346 try {
347 subscriber.onComplete();
348 } finally {
349 inner.dispose();
350 }
351 return;
352 }
353
354 subscriber.onNext(i++);
355
356 inner.schedule(this);
357 }
358 });
359 }
360 });
361
362 final AtomicInteger lastValue = new AtomicInteger();
363 obs.blockingForEach(new Consumer<Integer>() {
364
365 @Override
366 public void accept(Integer v) {
367 System.out.println("Value: " + v);
368 lastValue.set(v);
369 }
370 });
371
372 assertEquals(42, lastValue.get());
373 }
374
375 @Test
376 public final void concurrentOnNextFailsValidation() throws InterruptedException {
377 final int count = 10;
378 final CountDownLatch latch = new CountDownLatch(count);
379 Flowable<String> f = Flowable.unsafeCreate(new Publisher<String>() {
380
381 @Override
382 public void subscribe(final Subscriber<? super String> subscriber) {
383 subscriber.onSubscribe(new BooleanSubscription());
384 for (int i = 0; i < count; i++) {
385 final int v = i;
386 new Thread(new Runnable() {
387
388 @Override
389 public void run() {
390 subscriber.onNext("v: " + v);
391
392 latch.countDown();
393 }
394 }).start();
395 }
396 }
397 });
398
399 ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<>();
400 // this should call onNext concurrently
401 f.subscribe(observer);
402
403 if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) {
404 fail("timed out");
405 }
406
407 if (observer.error.get() == null) {
408 fail("We expected error messages due to concurrency");
409 }
410 }
411
412 @Test
413 public final void observeOn() throws InterruptedException {
414 final Scheduler scheduler = getScheduler();
415
416 Flowable<String> f = Flowable.fromArray("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten");
417
418 ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<>();
419
420 f.observeOn(scheduler).subscribe(observer);
421
422 if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) {
423 fail("timed out");
424 }
425
426 if (observer.error.get() != null) {
427 observer.error.get().printStackTrace();
428 fail("Error: " + observer.error.get().getMessage());
429 }
430 }
431
432 @Test
433 public final void subscribeOnNestedConcurrency() throws InterruptedException {
434 final Scheduler scheduler = getScheduler();
435
436 Flowable<String> f = Flowable.fromArray("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten")
437 .flatMap(new Function<String, Flowable<String>>() {
438
439 @Override
440 public Flowable<String> apply(final String v) {
441 return Flowable.unsafeCreate(new Publisher<String>() {
442
443 @Override
444 public void subscribe(Subscriber<? super String> subscriber) {
445 subscriber.onSubscribe(new BooleanSubscription());
446 subscriber.onNext("value_after_map-" + v);
447 subscriber.onComplete();
448 }
449 }).subscribeOn(scheduler);
450 }
451 });
452
453 ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<>();
454
455 f.subscribe(observer);
456
457 if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) {
458 fail("timed out");
459 }
460
461 if (observer.error.get() != null) {
462 observer.error.get().printStackTrace();
463 fail("Error: " + observer.error.get().getMessage());
464 }
465 }
466
467 /**
468 * Used to determine if onNext is being invoked concurrently.
469 *
470 * @param <T> the element type
471 */
472 private static class ConcurrentObserverValidator<T> extends DefaultSubscriber<T> {
473
474 final AtomicInteger concurrentCounter = new AtomicInteger();
475 final AtomicReference<Throwable> error = new AtomicReference<>();
476 final CountDownLatch completed = new CountDownLatch(1);
477
478 @Override
479 public void onComplete() {
480 completed.countDown();
481 }
482
483 @Override
484 public void onError(Throwable e) {
485 error.set(e);
486 completed.countDown();
487 }
488
489 @Override
490 public void onNext(T args) {
491 int count = concurrentCounter.incrementAndGet();
492 System.out.println("ConcurrentObserverValidator.onNext: " + args);
493 if (count > 1) {
494 onError(new RuntimeException("we should not have concurrent execution of onNext"));
495 }
496 try {
497 try {
498 // take some time so other onNext calls could pile up (I haven't yet thought of a way to do this without sleeping)
499 Thread.sleep(50);
500 } catch (InterruptedException e) {
501 // ignore
502 }
503 } finally {
504 concurrentCounter.decrementAndGet();
505 }
506 }
507
508 }
509
510 @Test
511 public void scheduleDirect() throws Exception {
512 Scheduler s = getScheduler();
513
514 final CountDownLatch cdl = new CountDownLatch(1);
515
516 s.scheduleDirect(new Runnable() {
517 @Override
518 public void run() {
519 cdl.countDown();
520 }
521 });
522
523 assertTrue(cdl.await(5, TimeUnit.SECONDS));
524 }
525
526 @Test
527 public void scheduleDirectDelayed() throws Exception {
528 Scheduler s = getScheduler();
529
530 final CountDownLatch cdl = new CountDownLatch(1);
531
532 s.scheduleDirect(new Runnable() {
533 @Override
534 public void run() {
535 cdl.countDown();
536 }
537 }, 50, TimeUnit.MILLISECONDS);
538
539 assertTrue(cdl.await(5, TimeUnit.SECONDS));
540 }
541
542 @Test
543 public void scheduleDirectPeriodic() throws Exception {
544 Scheduler s = getScheduler();
545 if (s instanceof TrampolineScheduler) {
546 // can't properly stop a trampolined periodic task
547 return;
548 }
549
550 final CountDownLatch cdl = new CountDownLatch(5);
551
552 Disposable d = s.schedulePeriodicallyDirect(new Runnable() {
553 @Override
554 public void run() {
555 cdl.countDown();
556 }
557 }, 10, 10, TimeUnit.MILLISECONDS);
558
559 try {
560 assertTrue(cdl.await(5, TimeUnit.SECONDS));
561 } finally {
562 d.dispose();
563 }
564 assertTrue(d.isDisposed());
565 }
566
567 @Test
568 public void schedulePeriodicallyDirectZeroPeriod() throws Exception {
569 Scheduler s = getScheduler();
570 if (s instanceof TrampolineScheduler) {
571 // can't properly stop a trampolined periodic task
572 return;
573 }
574
575 for (int initial = 0; initial < 2; initial++) {
576 final CountDownLatch cdl = new CountDownLatch(1);
577
578 final SequentialDisposable sd = new SequentialDisposable();
579
580 try {
581 sd.replace(s.schedulePeriodicallyDirect(new Runnable() {
582 int count;
583
584 @Override
585 public void run() {
586 if (++count == 10) {
587 sd.dispose();
588 cdl.countDown();
589 }
590 }
591 }, initial, 0, TimeUnit.MILLISECONDS));
592
593 assertTrue("" + initial, cdl.await(5, TimeUnit.SECONDS));
594 } finally {
595 sd.dispose();
596 }
597 }
598 }
599
600 @Test
601 public void schedulePeriodicallyZeroPeriod() throws Exception {
602 Scheduler s = getScheduler();
603 if (s instanceof TrampolineScheduler) {
604 // can't properly stop a trampolined periodic task
605 return;
606 }
607
608 for (int initial = 0; initial < 2; initial++) {
609 final CountDownLatch cdl = new CountDownLatch(1);
610
611 final SequentialDisposable sd = new SequentialDisposable();
612
613 Scheduler.Worker w = s.createWorker();
614
615 try {
616 sd.replace(w.schedulePeriodically(new Runnable() {
617 int count;
618
619 @Override
620 public void run() {
621 if (++count == 10) {
622 sd.dispose();
623 cdl.countDown();
624 }
625 }
626 }, initial, 0, TimeUnit.MILLISECONDS));
627
628 assertTrue("" + initial, cdl.await(5, TimeUnit.SECONDS));
629 } finally {
630 sd.dispose();
631 w.dispose();
632 }
633 }
634 }
635
636 private void assertRunnableDecorated(Runnable scheduleCall) throws InterruptedException {
637 try {
638 final CountDownLatch decoratedCalled = new CountDownLatch(1);
639
640 RxJavaPlugins.setScheduleHandler(new Function<Runnable, Runnable>() {
641 @Override
642 public Runnable apply(final Runnable actual) throws Exception {
643 return new Runnable() {
644 @Override
645 public void run() {
646 decoratedCalled.countDown();
647 actual.run();
648 }
649 };
650 }
651 });
652
653 scheduleCall.run();
654
655 assertTrue(decoratedCalled.await(5, TimeUnit.SECONDS));
656 } finally {
657 RxJavaPlugins.reset();
658 }
659 }
660
661 @Test
662 public void scheduleDirectDecoratesRunnable() throws InterruptedException {
663 assertRunnableDecorated(new Runnable() {
664 @Override
665 public void run() {
666 getScheduler().scheduleDirect(Functions.EMPTY_RUNNABLE);
667 }
668 });
669 }
670
671 @Test
672 public void scheduleDirectWithDelayDecoratesRunnable() throws InterruptedException {
673 assertRunnableDecorated(new Runnable() {
674 @Override
675 public void run() {
676 getScheduler().scheduleDirect(Functions.EMPTY_RUNNABLE, 1, TimeUnit.MILLISECONDS);
677 }
678 });
679 }
680
681 @Test
682 public void schedulePeriodicallyDirectDecoratesRunnable() throws InterruptedException {
683 final Scheduler scheduler = getScheduler();
684 if (scheduler instanceof TrampolineScheduler) {
685 // Can't properly stop a trampolined periodic task.
686 return;
687 }
688
689 final AtomicReference<Disposable> disposable = new AtomicReference<>();
690
691 try {
692 assertRunnableDecorated(new Runnable() {
693 @Override
694 public void run() {
695 disposable.set(scheduler.schedulePeriodicallyDirect(Functions.EMPTY_RUNNABLE, 1, 10000, TimeUnit.MILLISECONDS));
696 }
697 });
698 } finally {
699 disposable.get().dispose();
700 }
701 }
702
703 @Test
704 public void unwrapDefaultPeriodicTask() throws InterruptedException {
705 Scheduler s = getScheduler();
706 if (s instanceof TrampolineScheduler) {
707 // TrampolineScheduler always return EmptyDisposable
708 return;
709 }
710
711 final CountDownLatch cdl = new CountDownLatch(1);
712 Runnable countDownRunnable = new Runnable() {
713 @Override
714 public void run() {
715 cdl.countDown();
716 }
717 };
718 Disposable disposable = s.schedulePeriodicallyDirect(countDownRunnable, 100, 100, TimeUnit.MILLISECONDS);
719 SchedulerRunnableIntrospection wrapper = (SchedulerRunnableIntrospection) disposable;
720
721 assertSame(countDownRunnable, wrapper.getWrappedRunnable());
722 assertTrue(cdl.await(5, TimeUnit.SECONDS));
723 disposable.dispose();
724 }
725
726 @Test
727 public void unwrapScheduleDirectTask() {
728 Scheduler scheduler = getScheduler();
729 if (scheduler instanceof TrampolineScheduler) {
730 // TrampolineScheduler always return EmptyDisposable
731 return;
732 }
733 final CountDownLatch cdl = new CountDownLatch(1);
734 Runnable countDownRunnable = new Runnable() {
735 @Override
736 public void run() {
737 cdl.countDown();
738 }
739 };
740 Disposable disposable = scheduler.scheduleDirect(countDownRunnable, 100, TimeUnit.MILLISECONDS);
741 SchedulerRunnableIntrospection wrapper = (SchedulerRunnableIntrospection) disposable;
742 assertSame(countDownRunnable, wrapper.getWrappedRunnable());
743 disposable.dispose();
744 }
745
746 @Test
747 public void scheduleDirectNullRunnable() {
748 try {
749 getScheduler().scheduleDirect(null);
750 fail();
751 } catch (NullPointerException npe) {
752 assertEquals("run is null", npe.getMessage());
753 }
754 }
755
756 @Test
757 public void scheduleDirectWithDelayNullRunnable() {
758 try {
759 getScheduler().scheduleDirect(null, 10, TimeUnit.MILLISECONDS);
760 fail();
761 } catch (NullPointerException npe) {
762 assertEquals("run is null", npe.getMessage());
763 }
764 }
765
766 @Test
767 public void schedulePeriodicallyDirectNullRunnable() {
768 try {
769 getScheduler().schedulePeriodicallyDirect(null, 5, 10, TimeUnit.MILLISECONDS);
770 fail();
771 } catch (NullPointerException npe) {
772 assertEquals("run is null", npe.getMessage());
773 }
774 }
775
776 void schedulePrint(Function<Runnable, Disposable> onSchedule) {
777 CountDownLatch waitForBody = new CountDownLatch(1);
778 CountDownLatch waitForPrint = new CountDownLatch(1);
779
780 try {
781 Disposable d = onSchedule.apply(() -> {
782 waitForBody.countDown();
783 try {
784 waitForPrint.await();
785 } catch (InterruptedException ex) {
786 ex.printStackTrace();
787 }
788 });
789
790 waitForBody.await();
791
792 assertNotEquals("", d.toString());
793 } catch (Throwable ex) {
794 throw new AssertionError(ex);
795 } finally {
796 waitForPrint.countDown();
797 }
798 }
799
800 @Test
801 public void scheduleDirectPrint() {
802 if (getScheduler() instanceof TrampolineScheduler) {
803 // no concurrency with Trampoline
804 return;
805 }
806 schedulePrint(r -> getScheduler().scheduleDirect(r));
807 }
808
809 @Test
810 public void schedulePrint() {
811 if (getScheduler() instanceof TrampolineScheduler) {
812 // no concurrency with Trampoline
813 return;
814 }
815 Worker worker = getScheduler().createWorker();
816 try {
817 schedulePrint(worker::schedule);
818 } finally {
819 worker.dispose();
820 }
821 }
822 }