Debian Codegraph @

src/test/java/io/reactivex/rxjava3/observers/SerializedObserverTest.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.observers;
15
16 import static org.junit.Assert.*;
17 import static org.mockito.ArgumentMatchers.any;
18 import static org.mockito.Mockito.*;
19
20 import java.util.List;
21 import java.util.concurrent.*;
22 import java.util.concurrent.atomic.*;
23
24 import org.junit.*;
25
26 import io.reactivex.rxjava3.core.*;
27 import io.reactivex.rxjava3.disposables.Disposable;
28 import io.reactivex.rxjava3.exceptions.TestException;
29 import io.reactivex.rxjava3.internal.util.ExceptionHelper;
30 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
31 import io.reactivex.rxjava3.schedulers.Schedulers;
32 import io.reactivex.rxjava3.testsupport.*;
33
34 public class SerializedObserverTest extends RxJavaTest {
35
36 Observer<String> observer;
37
38 @Before
39 public void before() {
40 observer = TestHelper.mockObserver();
41 }
42
43 private Observer<String> serializedObserver(Observer<String> o) {
44 return new SerializedObserver<>(o);
45 }
46
47 @Test
48 public void singleThreadedBasic() {
49 TestSingleThreadedObservable onSubscribe = new TestSingleThreadedObservable("one", "two", "three");
50 Observable<String> w = Observable.unsafeCreate(onSubscribe);
51
52 Observer<String> aw = serializedObserver(observer);
53
54 w.subscribe(aw);
55 onSubscribe.waitToFinish();
56
57 verify(observer, times(1)).onNext("one");
58 verify(observer, times(1)).onNext("two");
59 verify(observer, times(1)).onNext("three");
60 verify(observer, never()).onError(any(Throwable.class));
61 verify(observer, times(1)).onComplete();
62 // non-deterministic because unsubscribe happens after 'waitToFinish' releases
63 // so commenting out for now as this is not a critical thing to test here
64 // verify(s, times(1)).unsubscribe();
65 }
66
67 @Test
68 public void multiThreadedBasic() {
69 TestMultiThreadedObservable onSubscribe = new TestMultiThreadedObservable("one", "two", "three");
70 Observable<String> w = Observable.unsafeCreate(onSubscribe);
71
72 BusyObserver busySubscriber = new BusyObserver();
73 Observer<String> aw = serializedObserver(busySubscriber);
74
75 w.subscribe(aw);
76 onSubscribe.waitToFinish();
77
78 assertEquals(3, busySubscriber.onNextCount.get());
79 assertFalse(busySubscriber.onError);
80 assertTrue(busySubscriber.onComplete);
81 // non-deterministic because unsubscribe happens after 'waitToFinish' releases
82 // so commenting out for now as this is not a critical thing to test here
83 // verify(s, times(1)).unsubscribe();
84
85 // we can have concurrency ...
86 assertTrue(onSubscribe.maxConcurrentThreads.get() > 1);
87 // ... but the onNext execution should be single threaded
88 assertEquals(1, busySubscriber.maxConcurrentThreads.get());
89 }
90
91 @Test
92 public void multiThreadedWithNPE() throws InterruptedException {
93 TestMultiThreadedObservable onSubscribe = new TestMultiThreadedObservable("one", "two", "three", null);
94 Observable<String> w = Observable.unsafeCreate(onSubscribe);
95
96 BusyObserver busySubscriber = new BusyObserver();
97 Observer<String> aw = serializedObserver(busySubscriber);
98
99 w.subscribe(aw);
100 onSubscribe.waitToFinish();
101 busySubscriber.terminalEvent.await();
102
103 System.out.println("OnSubscribe maxConcurrentThreads: " + onSubscribe.maxConcurrentThreads.get() + " Observer maxConcurrentThreads: " + busySubscriber.maxConcurrentThreads.get());
104
105 // we can't know how many onNext calls will occur since they each run on a separate thread
106 // that depends on thread scheduling so 0, 1, 2 and 3 are all valid options
107 // assertEquals(3, busySubscriber.onNextCount.get());
108 assertTrue(busySubscriber.onNextCount.get() < 4);
109 assertTrue(busySubscriber.onError);
110 // no onComplete because onError was invoked
111 assertFalse(busySubscriber.onComplete);
112 // non-deterministic because unsubscribe happens after 'waitToFinish' releases
113 // so commenting out for now as this is not a critical thing to test here
114 //verify(s, times(1)).unsubscribe();
115
116 // we can have concurrency ...
117 assertTrue(onSubscribe.maxConcurrentThreads.get() > 1);
118 // ... but the onNext execution should be single threaded
119 assertEquals(1, busySubscriber.maxConcurrentThreads.get());
120 }
121
122 @Test
123 public void multiThreadedWithNPEinMiddle() {
124 int n = 10;
125 for (int i = 0; i < n; i++) {
126 TestMultiThreadedObservable onSubscribe = new TestMultiThreadedObservable("one", "two", "three", null,
127 "four", "five", "six", "seven", "eight", "nine");
128 Observable<String> w = Observable.unsafeCreate(onSubscribe);
129
130 BusyObserver busySubscriber = new BusyObserver();
131 Observer<String> aw = serializedObserver(busySubscriber);
132
133 w.subscribe(aw);
134 onSubscribe.waitToFinish();
135
136 System.out.println("OnSubscribe maxConcurrentThreads: " + onSubscribe.maxConcurrentThreads.get() + " Observer maxConcurrentThreads: " + busySubscriber.maxConcurrentThreads.get());
137
138 // we can have concurrency ...
139 assertTrue(onSubscribe.maxConcurrentThreads.get() > 1);
140 // ... but the onNext execution should be single threaded
141 assertEquals(1, busySubscriber.maxConcurrentThreads.get());
142
143 // this should not be the full number of items since the error should stop it before it completes all 9
144 System.out.println("onNext count: " + busySubscriber.onNextCount.get());
145 assertFalse(busySubscriber.onComplete);
146 assertTrue(busySubscriber.onError);
147 assertTrue(busySubscriber.onNextCount.get() < 9);
148 // no onComplete because onError was invoked
149 // non-deterministic because unsubscribe happens after 'waitToFinish' releases
150 // so commenting out for now as this is not a critical thing to test here
151 // verify(s, times(1)).unsubscribe();
152 }
153 }
154
155 /**
156 * A non-realistic use case that tries to expose thread-safety issues by throwing lots of out-of-order
157 * events on many threads.
158 */
159 @Test
160 public void runOutOfOrderConcurrencyTest() {
161 ExecutorService tp = Executors.newFixedThreadPool(20);
162 List<Throwable> errors = TestHelper.trackPluginErrors();
163 try {
164 TestConcurrencySubscriber tw = new TestConcurrencySubscriber();
165 // we need Synchronized + SafeObserver to handle synchronization plus life-cycle
166 Observer<String> w = serializedObserver(new SafeObserver<>(tw));
167
168 Future<?> f1 = tp.submit(new OnNextThread(w, 12000));
169 Future<?> f2 = tp.submit(new OnNextThread(w, 5000));
170 Future<?> f3 = tp.submit(new OnNextThread(w, 75000));
171 Future<?> f4 = tp.submit(new OnNextThread(w, 13500));
172 Future<?> f5 = tp.submit(new OnNextThread(w, 22000));
173 Future<?> f6 = tp.submit(new OnNextThread(w, 15000));
174 Future<?> f7 = tp.submit(new OnNextThread(w, 7500));
175 Future<?> f8 = tp.submit(new OnNextThread(w, 23500));
176
177 Future<?> f10 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f1, f2, f3, f4));
178 try {
179 Thread.sleep(1);
180 } catch (InterruptedException e) {
181 // ignore
182 }
183 Future<?> f11 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
184 Future<?> f12 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
185 Future<?> f13 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
186 Future<?> f14 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
187 // // the next 4 onError events should wait on same as f10
188 Future<?> f15 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
189 Future<?> f16 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
190 Future<?> f17 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
191 Future<?> f18 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
192
193 waitOnThreads(f1, f2, f3, f4, f5, f6, f7, f8, f10, f11, f12, f13, f14, f15, f16, f17, f18);
194 @SuppressWarnings("unused")
195 int numNextEvents = tw.assertEvents(null); // no check of type since we don't want to test barging results here, just interleaving behavior
196 // System.out.println("Number of events executed: " + numNextEvents);
197
198 for (int i = 0; i < errors.size(); i++) {
199 TestHelper.assertUndeliverable(errors, i, RuntimeException.class);
200 }
201 } catch (Throwable e) {
202 fail("Concurrency test failed: " + e.getMessage());
203 e.printStackTrace();
204 } finally {
205 tp.shutdown();
206 try {
207 tp.awaitTermination(5000, TimeUnit.MILLISECONDS);
208 } catch (InterruptedException e) {
209 e.printStackTrace();
210 }
211
212 RxJavaPlugins.reset();
213 }
214 }
215
216 @Test
217 public void runConcurrencyTest() {
218 ExecutorService tp = Executors.newFixedThreadPool(20);
219 try {
220 TestConcurrencySubscriber tw = new TestConcurrencySubscriber();
221 // we need Synchronized + SafeObserver to handle synchronization plus life-cycle
222 Observer<String> w = serializedObserver(new SafeObserver<>(tw));
223 w.onSubscribe(Disposable.empty());
224
225 Future<?> f1 = tp.submit(new OnNextThread(w, 12000));
226 Future<?> f2 = tp.submit(new OnNextThread(w, 5000));
227 Future<?> f3 = tp.submit(new OnNextThread(w, 75000));
228 Future<?> f4 = tp.submit(new OnNextThread(w, 13500));
229 Future<?> f5 = tp.submit(new OnNextThread(w, 22000));
230 Future<?> f6 = tp.submit(new OnNextThread(w, 15000));
231 Future<?> f7 = tp.submit(new OnNextThread(w, 7500));
232 Future<?> f8 = tp.submit(new OnNextThread(w, 23500));
233
234 // 12000 + 5000 + 75000 + 13500 + 22000 + 15000 + 7500 + 23500 = 173500
235
236 Future<?> f10 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f1, f2, f3, f4, f5, f6, f7, f8));
237 try {
238 Thread.sleep(1);
239 } catch (InterruptedException e) {
240 // ignore
241 }
242
243 waitOnThreads(f1, f2, f3, f4, f5, f6, f7, f8, f10);
244 int numNextEvents = tw.assertEvents(null); // no check of type since we don't want to test barging results here, just interleaving behavior
245 assertEquals(173500, numNextEvents);
246 // System.out.println("Number of events executed: " + numNextEvents);
247 } catch (Throwable e) {
248 fail("Concurrency test failed: " + e.getMessage());
249 e.printStackTrace();
250 } finally {
251 tp.shutdown();
252 try {
253 tp.awaitTermination(25000, TimeUnit.MILLISECONDS);
254 } catch (InterruptedException e) {
255 e.printStackTrace();
256 }
257 }
258 }
259
260 /**
261 * Test that a notification does not get delayed in the queue waiting for the next event to push it through.
262 *
263 * @throws InterruptedException if the await is interrupted
264 */
265 @Ignore("this is non-deterministic ... haven't figured out what's wrong with the test yet (benjchristensen: July 2014)")
266 @Test
267 public void notificationDelay() throws InterruptedException {
268 ExecutorService tp1 = Executors.newFixedThreadPool(1);
269 ExecutorService tp2 = Executors.newFixedThreadPool(1);
270 try {
271 int n = 10;
272 for (int i = 0; i < n; i++) {
273 final CountDownLatch firstOnNext = new CountDownLatch(1);
274 final CountDownLatch onNextCount = new CountDownLatch(2);
275 final CountDownLatch latch = new CountDownLatch(1);
276 final CountDownLatch running = new CountDownLatch(2);
277
278 TestObserverEx<String> to = new TestObserverEx<>(new DefaultObserver<String>() {
279
280 @Override
281 public void onComplete() {
282
283 }
284
285 @Override
286 public void onError(Throwable e) {
287
288 }
289
290 @Override
291 public void onNext(String t) {
292 firstOnNext.countDown();
293 // force it to take time when delivering so the second one is enqueued
294 try {
295 latch.await();
296 } catch (InterruptedException e) {
297 }
298 }
299
300 });
301 Observer<String> o = serializedObserver(to);
302
303 Future<?> f1 = tp1.submit(new OnNextThread(o, 1, onNextCount, running));
304 Future<?> f2 = tp2.submit(new OnNextThread(o, 1, onNextCount, running));
305
306 running.await(); // let one of the OnNextThread actually run before proceeding
307
308 firstOnNext.await();
309
310 Thread t1 = to.lastThread();
311 System.out.println("first onNext on thread: " + t1);
312
313 latch.countDown();
314
315 waitOnThreads(f1, f2);
316 // not completed yet
317
318 assertEquals(2, to.values().size());
319
320 Thread t2 = to.lastThread();
321 System.out.println("second onNext on thread: " + t2);
322
323 assertSame(t1, t2);
324
325 System.out.println(to.values());
326 o.onComplete();
327 System.out.println(to.values());
328 }
329 } finally {
330 tp1.shutdown();
331 tp2.shutdown();
332 }
333 }
334
335 /**
336 * Demonstrates thread starvation problem.
337 *
338 * No solution on this for now. Trade-off in this direction as per https://github.com/ReactiveX/RxJava/issues/998#issuecomment-38959474
339 * Probably need backpressure for this to work
340 *
341 * When using SynchronizedSubscriber we get this output:
342 *
343 * {@code p1: 18 p2: 68 =>} should be close to each other unless we have thread starvation
344 *
345 * When using SerializedObserver we get:
346 *
347 * {@code p1: 1 p2: 2445261 =>} should be close to each other unless we have thread starvation
348 *
349 * This demonstrates how SynchronizedSubscriber balances back and forth better, and blocks emission.
350 * The real issue in this example is the async buffer-bloat, so we need backpressure.
351 *
352 *
353 * @throws InterruptedException if the await is interrupted
354 */
355 @Ignore("Demonstrates thread starvation problem. Read JavaDoc")
356 @Test
357 public void threadStarvation() throws InterruptedException {
358
359 TestObserver<String> to = new TestObserver<>(new DefaultObserver<String>() {
360
361 @Override
362 public void onComplete() {
363
364 }
365
366 @Override
367 public void onError(Throwable e) {
368
369 }
370
371 @Override
372 public void onNext(String t) {
373 // force it to take time when delivering
374 try {
375 Thread.sleep(1);
376 } catch (InterruptedException e) {
377 }
378 }
379
380 });
381 final Observer<String> o = serializedObserver(to);
382
383 AtomicInteger p1 = new AtomicInteger();
384 AtomicInteger p2 = new AtomicInteger();
385
386 o.onSubscribe(Disposable.empty());
387 DisposableObserver<String> as1 = new DisposableObserver<String>() {
388 @Override
389 public void onNext(String t) {
390 o.onNext(t);
391 }
392
393 @Override
394 public void onError(Throwable t) {
395 RxJavaPlugins.onError(t);
396 }
397
398 @Override
399 public void onComplete() {
400
401 }
402 };
403
404 DisposableObserver<String> as2 = new DisposableObserver<String>() {
405 @Override
406 public void onNext(String t) {
407 o.onNext(t);
408 }
409
410 @Override
411 public void onError(Throwable t) {
412 RxJavaPlugins.onError(t);
413 }
414
415 @Override
416 public void onComplete() {
417
418 }
419 };
420
421 infinite(p1).subscribe(as1);
422 infinite(p2).subscribe(as2);
423
424 Thread.sleep(100);
425
426 System.out.println("p1: " + p1.get() + " p2: " + p2.get() + " => should be close to each other unless we have thread starvation");
427 assertEquals(p1.get(), p2.get(), 10000); // fairly distributed within 10000 of each other
428
429 as1.dispose();
430 as2.dispose();
431 }
432
433 private static void waitOnThreads(Future<?>... futures) {
434 for (Future<?> f : futures) {
435 try {
436 f.get(20, TimeUnit.SECONDS);
437 } catch (Throwable e) {
438 System.err.println("Failed while waiting on future.");
439 e.printStackTrace();
440 }
441 }
442 }
443
444 private static Observable<String> infinite(final AtomicInteger produced) {
445 return Observable.unsafeCreate(new ObservableSource<String>() {
446
447 @Override
448 public void subscribe(Observer<? super String> observer) {
449 Disposable bs = Disposable.empty();
450 observer.onSubscribe(bs);
451 while (!bs.isDisposed()) {
452 observer.onNext("onNext");
453 produced.incrementAndGet();
454 }
455 }
456
457 }).subscribeOn(Schedulers.newThread());
458 }
459
460 /**
461 * A thread that will pass data to onNext.
462 */
463 public static class OnNextThread implements Runnable {
464
465 private final CountDownLatch latch;
466 private final Observer<String> observer;
467 private final int numStringsToSend;
468 final AtomicInteger produced;
469 private final CountDownLatch running;
470
471 OnNextThread(Observer<String> observer, int numStringsToSend, CountDownLatch latch, CountDownLatch running) {
472 this(observer, numStringsToSend, new AtomicInteger(), latch, running);
473 }
474
475 OnNextThread(Observer<String> observer, int numStringsToSend, AtomicInteger produced) {
476 this(observer, numStringsToSend, produced, null, null);
477 }
478
479 OnNextThread(Observer<String> observer, int numStringsToSend, AtomicInteger produced, CountDownLatch latch, CountDownLatch running) {
480 this.observer = observer;
481 this.numStringsToSend = numStringsToSend;
482 this.produced = produced;
483 this.latch = latch;
484 this.running = running;
485 }
486
487 OnNextThread(Observer<String> observer, int numStringsToSend) {
488 this(observer, numStringsToSend, new AtomicInteger());
489 }
490
491 @Override
492 public void run() {
493 if (running != null) {
494 running.countDown();
495 }
496 for (int i = 0; i < numStringsToSend; i++) {
497 observer.onNext(Thread.currentThread().getId() + "-" + i);
498 if (latch != null) {
499 latch.countDown();
500 }
501 produced.incrementAndGet();
502 }
503 }
504 }
505
506 /**
507 * A thread that will call onError or onNext.
508 */
509 public static class CompletionThread implements Runnable {
510
511 private final Observer<String> observer;
512 private final TestConcurrencySubscriberEvent event;
513 private final Future<?>[] waitOnThese;
514
515 CompletionThread(Observer<String> Observer, TestConcurrencySubscriberEvent event, Future<?>... waitOnThese) {
516 this.observer = Observer;
517 this.event = event;
518 this.waitOnThese = waitOnThese;
519 }
520
521 @Override
522 public void run() {
523 /* if we have 'waitOnThese' futures, we'll wait on them before proceeding */
524 if (waitOnThese != null) {
525 for (Future<?> f : waitOnThese) {
526 try {
527 f.get();
528 } catch (Throwable e) {
529 System.err.println("Error while waiting on future in CompletionThread");
530 }
531 }
532 }
533
534 /* send the event */
535 if (event == TestConcurrencySubscriberEvent.onError) {
536 observer.onError(new RuntimeException("mocked exception"));
537 } else if (event == TestConcurrencySubscriberEvent.onComplete) {
538 observer.onComplete();
539
540 } else {
541 throw new IllegalArgumentException("Expecting either onError or onComplete");
542 }
543 }
544 }
545
546 enum TestConcurrencySubscriberEvent {
547 onComplete, onError, onNext
548 }
549
550 private static class TestConcurrencySubscriber extends DefaultObserver<String> {
551
552 /**
553 * used to store the order and number of events received.
554 */
555 private final LinkedBlockingQueue<TestConcurrencySubscriberEvent> events = new LinkedBlockingQueue<>();
556 private final int waitTime;
557
558 @SuppressWarnings("unused")
559 TestConcurrencySubscriber(int waitTimeInNext) {
560 this.waitTime = waitTimeInNext;
561 }
562
563 TestConcurrencySubscriber() {
564 this.waitTime = 0;
565 }
566
567 @Override
568 public void onComplete() {
569 events.add(TestConcurrencySubscriberEvent.onComplete);
570 }
571
572 @Override
573 public void onError(Throwable e) {
574 events.add(TestConcurrencySubscriberEvent.onError);
575 }
576
577 @Override
578 public void onNext(String args) {
579 events.add(TestConcurrencySubscriberEvent.onNext);
580 // do some artificial work to make the thread scheduling/timing vary
581 int s = 0;
582 for (int i = 0; i < 20; i++) {
583 s += s * i;
584 }
585
586 if (waitTime > 0) {
587 try {
588 Thread.sleep(waitTime);
589 } catch (InterruptedException e) {
590 // ignore
591 }
592 }
593 }
594
595 /**
596 * Assert the order of events is correct and return the number of onNext executions.
597 *
598 * @param expectedEndingEvent the expected last event
599 * @return int count of onNext calls
600 * @throws IllegalStateException
601 * If order of events was invalid.
602 */
603 public int assertEvents(TestConcurrencySubscriberEvent expectedEndingEvent) throws IllegalStateException {
604 int nextCount = 0;
605 boolean finished = false;
606 for (TestConcurrencySubscriberEvent e : events) {
607 if (e == TestConcurrencySubscriberEvent.onNext) {
608 if (finished) {
609 // already finished, we shouldn't get this again
610 throw new IllegalStateException("Received onNext but we're already finished.");
611 }
612 nextCount++;
613 } else if (e == TestConcurrencySubscriberEvent.onError) {
614 if (finished) {
615 // already finished, we shouldn't get this again
616 throw new IllegalStateException("Received onError but we're already finished.");
617 }
618 if (expectedEndingEvent != null && TestConcurrencySubscriberEvent.onError != expectedEndingEvent) {
619 throw new IllegalStateException("Received onError ending event but expected " + expectedEndingEvent);
620 }
621 finished = true;
622 } else if (e == TestConcurrencySubscriberEvent.onComplete) {
623 if (finished) {
624 // already finished, we shouldn't get this again
625 throw new IllegalStateException("Received onComplete but we're already finished.");
626 }
627 if (expectedEndingEvent != null && TestConcurrencySubscriberEvent.onComplete != expectedEndingEvent) {
628 throw new IllegalStateException("Received onComplete ending event but expected " + expectedEndingEvent);
629 }
630 finished = true;
631 }
632 }
633
634 return nextCount;
635 }
636
637 }
638
639 /**
640 * This spawns a single thread for the subscribe execution.
641 */
642 private static class TestSingleThreadedObservable implements ObservableSource<String> {
643
644 final String[] values;
645 private Thread t;
646
647 TestSingleThreadedObservable(final String... values) {
648 this.values = values;
649
650 }
651
652 @Override
653 public void subscribe(final Observer<? super String> observer) {
654 observer.onSubscribe(Disposable.empty());
655 System.out.println("TestSingleThreadedObservable subscribed to ...");
656 t = new Thread(new Runnable() {
657
658 @Override
659 public void run() {
660 try {
661 System.out.println("running TestSingleThreadedObservable thread");
662 for (String s : values) {
663 System.out.println("TestSingleThreadedObservable onNext: " + s);
664 observer.onNext(s);
665 }
666 observer.onComplete();
667 } catch (Throwable e) {
668 throw new RuntimeException(e);
669 }
670 }
671
672 });
673 System.out.println("starting TestSingleThreadedObservable thread");
674 t.start();
675 System.out.println("done starting TestSingleThreadedObservable thread");
676 }
677
678 public void waitToFinish() {
679 try {
680 t.join();
681 } catch (InterruptedException e) {
682 throw new RuntimeException(e);
683 }
684 }
685
686 }
687
688 /**
689 * This spawns a thread for the subscription, then a separate thread for each onNext call.
690 */
691 private static class TestMultiThreadedObservable implements ObservableSource<String> {
692
693 final String[] values;
694 Thread t;
695 AtomicInteger threadsRunning = new AtomicInteger();
696 AtomicInteger maxConcurrentThreads = new AtomicInteger();
697 ExecutorService threadPool;
698
699 TestMultiThreadedObservable(String... values) {
700 this.values = values;
701 this.threadPool = Executors.newCachedThreadPool();
702 }
703
704 @Override
705 public void subscribe(final Observer<? super String> observer) {
706 observer.onSubscribe(Disposable.empty());
707 final NullPointerException npe = new NullPointerException();
708 System.out.println("TestMultiThreadedObservable subscribed to ...");
709 t = new Thread(new Runnable() {
710
711 @Override
712 public void run() {
713 try {
714 System.out.println("running TestMultiThreadedObservable thread");
715 int j = 0;
716 for (final String s : values) {
717 final int fj = ++j;
718 threadPool.execute(new Runnable() {
719
720 @Override
721 public void run() {
722 threadsRunning.incrementAndGet();
723 try {
724 // perform onNext call
725 System.out.println("TestMultiThreadedObservable onNext: " + s + " on thread " + Thread.currentThread().getName());
726 if (s == null) {
727 // force an error
728 throw npe;
729 } else {
730 // allow the exception to queue up
731 int sleep = (fj % 3) * 10;
732 if (sleep != 0) {
733 Thread.sleep(sleep);
734 }
735 }
736 observer.onNext(s);
737 // capture 'maxThreads'
738 int concurrentThreads = threadsRunning.get();
739 int maxThreads = maxConcurrentThreads.get();
740 if (concurrentThreads > maxThreads) {
741 maxConcurrentThreads.compareAndSet(maxThreads, concurrentThreads);
742 }
743 } catch (Throwable e) {
744 observer.onError(e);
745 } finally {
746 threadsRunning.decrementAndGet();
747 }
748 }
749 });
750 }
751 // we are done spawning threads
752 threadPool.shutdown();
753 } catch (Throwable e) {
754 throw new RuntimeException(e);
755 }
756
757 // wait until all threads are done, then mark it as COMPLETED
758 try {
759 // wait for all the threads to finish
760 if (!threadPool.awaitTermination(5, TimeUnit.SECONDS)) {
761 System.out.println("Threadpool did not terminate in time.");
762 }
763 } catch (InterruptedException e) {
764 throw new RuntimeException(e);
765 }
766 observer.onComplete();
767 }
768 });
769 System.out.println("starting TestMultiThreadedObservable thread");
770 t.start();
771 System.out.println("done starting TestMultiThreadedObservable thread");
772 }
773
774 public void waitToFinish() {
775 try {
776 t.join();
777 } catch (InterruptedException e) {
778 throw new RuntimeException(e);
779 }
780 }
781 }
782
783 static class BusyObserver extends DefaultObserver<String> {
784 volatile boolean onComplete;
785 volatile boolean onError;
786 AtomicInteger onNextCount = new AtomicInteger();
787 AtomicInteger threadsRunning = new AtomicInteger();
788 AtomicInteger maxConcurrentThreads = new AtomicInteger();
789 final CountDownLatch terminalEvent = new CountDownLatch(1);
790
791 @Override
792 public void onComplete() {
793 threadsRunning.incrementAndGet();
794 try {
795 onComplete = true;
796 } finally {
797 captureMaxThreads();
798 threadsRunning.decrementAndGet();
799 terminalEvent.countDown();
800 }
801 }
802
803 @Override
804 public void onError(Throwable e) {
805 System.out.println(">>>>>>>>>>>>>>>>>>>> onError received: " + e);
806 threadsRunning.incrementAndGet();
807 try {
808 onError = true;
809 } finally {
810 captureMaxThreads();
811 threadsRunning.decrementAndGet();
812 terminalEvent.countDown();
813 }
814 }
815
816 @Override
817 public void onNext(String args) {
818 threadsRunning.incrementAndGet();
819 try {
820 onNextCount.incrementAndGet();
821 try {
822 // simulate doing something computational
823 Thread.sleep(100);
824 } catch (InterruptedException e) {
825 e.printStackTrace();
826 }
827 } finally {
828 // capture 'maxThreads'
829 captureMaxThreads();
830 threadsRunning.decrementAndGet();
831 }
832 }
833
834 protected void captureMaxThreads() {
835 int concurrentThreads = threadsRunning.get();
836 int maxThreads = maxConcurrentThreads.get();
837 if (concurrentThreads > maxThreads) {
838 maxConcurrentThreads.compareAndSet(maxThreads, concurrentThreads);
839 if (concurrentThreads > 1) {
840 new RuntimeException("should not be greater than 1").printStackTrace();
841 }
842 }
843 }
844
845 }
846
847 @Test
848 public void errorReentry() {
849 List<Throwable> errors = TestHelper.trackPluginErrors();
850 try {
851 final AtomicReference<Observer<Integer>> serial = new AtomicReference<>();
852
853 TestObserver<Integer> to = new TestObserver<Integer>() {
854 @Override
855 public void onNext(Integer v) {
856 serial.get().onError(new TestException());
857 serial.get().onError(new TestException());
858 super.onNext(v);
859 }
860 };
861 SerializedObserver<Integer> sobs = new SerializedObserver<>(to);
862 sobs.onSubscribe(Disposable.empty());
863 serial.set(sobs);
864
865 sobs.onNext(1);
866
867 to.assertValue(1);
868 to.assertError(TestException.class);
869
870 TestHelper.assertUndeliverable(errors, 0, TestException.class);
871 } finally {
872 RxJavaPlugins.reset();
873 }
874 }
875
876 @Test
877 public void completeReentry() {
878 final AtomicReference<Observer<Integer>> serial = new AtomicReference<>();
879
880 TestObserver<Integer> to = new TestObserver<Integer>() {
881 @Override
882 public void onNext(Integer v) {
883 serial.get().onComplete();
884 serial.get().onComplete();
885 super.onNext(v);
886 }
887 };
888 SerializedObserver<Integer> sobs = new SerializedObserver<>(to);
889 sobs.onSubscribe(Disposable.empty());
890 serial.set(sobs);
891
892 sobs.onNext(1);
893
894 to.assertValue(1);
895 to.assertComplete();
896 to.assertNoErrors();
897 }
898
899 @Test
900 public void dispose() {
901 TestObserver<Integer> to = new TestObserver<>();
902
903 SerializedObserver<Integer> so = new SerializedObserver<>(to);
904
905 Disposable d = Disposable.empty();
906
907 so.onSubscribe(d);
908
909 assertFalse(so.isDisposed());
910
911 to.dispose();
912
913 assertTrue(so.isDisposed());
914
915 assertTrue(d.isDisposed());
916 }
917
918 @Test
919 public void onCompleteRace() {
920 for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
921 TestObserver<Integer> to = new TestObserver<>();
922
923 final SerializedObserver<Integer> so = new SerializedObserver<>(to);
924
925 Disposable d = Disposable.empty();
926
927 so.onSubscribe(d);
928
929 Runnable r = new Runnable() {
930 @Override
931 public void run() {
932 so.onComplete();
933 }
934 };
935
936 TestHelper.race(r, r);
937
938 to.awaitDone(5, TimeUnit.SECONDS)
939 .assertResult();
940 }
941
942 }
943
944 @Test
945 public void onNextOnCompleteRace() {
946 for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
947 TestObserver<Integer> to = new TestObserver<>();
948
949 final SerializedObserver<Integer> so = new SerializedObserver<>(to);
950
951 Disposable d = Disposable.empty();
952
953 so.onSubscribe(d);
954
955 Runnable r1 = new Runnable() {
956 @Override
957 public void run() {
958 so.onComplete();
959 }
960 };
961
962 Runnable r2 = new Runnable() {
963 @Override
964 public void run() {
965 so.onNext(1);
966 }
967 };
968
969 TestHelper.race(r1, r2);
970
971 to.awaitDone(5, TimeUnit.SECONDS)
972 .assertNoErrors()
973 .assertComplete();
974
975 assertTrue(to.values().size() <= 1);
976 }
977
978 }
979
980 @Test
981 public void onNextOnErrorRace() {
982 for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
983 TestObserver<Integer> to = new TestObserver<>();
984
985 final SerializedObserver<Integer> so = new SerializedObserver<>(to);
986
987 Disposable d = Disposable.empty();
988
989 so.onSubscribe(d);
990
991 final Throwable ex = new TestException();
992
993 Runnable r1 = new Runnable() {
994 @Override
995 public void run() {
996 so.onError(ex);
997 }
998 };
999
1000 Runnable r2 = new Runnable() {
1001 @Override
1002 public void run() {
1003 so.onNext(1);
1004 }
1005 };
1006
1007 TestHelper.race(r1, r2);
1008
1009 to.awaitDone(5, TimeUnit.SECONDS)
1010 .assertError(ex)
1011 .assertNotComplete();
1012
1013 assertTrue(to.values().size() <= 1);
1014 }
1015
1016 }
1017
1018 @Test
1019 public void onNextOnErrorRaceDelayError() {
1020 for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
1021 TestObserver<Integer> to = new TestObserver<>();
1022
1023 final SerializedObserver<Integer> so = new SerializedObserver<>(to, true);
1024
1025 Disposable d = Disposable.empty();
1026
1027 so.onSubscribe(d);
1028
1029 final Throwable ex = new TestException();
1030
1031 Runnable r1 = new Runnable() {
1032 @Override
1033 public void run() {
1034 so.onError(ex);
1035 }
1036 };
1037
1038 Runnable r2 = new Runnable() {
1039 @Override
1040 public void run() {
1041 so.onNext(1);
1042 }
1043 };
1044
1045 TestHelper.race(r1, r2);
1046
1047 to.awaitDone(5, TimeUnit.SECONDS)
1048 .assertError(ex)
1049 .assertNotComplete();
1050
1051 assertTrue(to.values().size() <= 1);
1052 }
1053
1054 }
1055
1056 @Test
1057 public void startOnce() {
1058
1059 List<Throwable> error = TestHelper.trackPluginErrors();
1060
1061 try {
1062 TestObserver<Integer> to = new TestObserver<>();
1063
1064 final SerializedObserver<Integer> so = new SerializedObserver<>(to);
1065
1066 so.onSubscribe(Disposable.empty());
1067
1068 Disposable d = Disposable.empty();
1069
1070 so.onSubscribe(d);
1071
1072 assertTrue(d.isDisposed());
1073
1074 TestHelper.assertError(error, 0, IllegalStateException.class, "Disposable already set!");
1075 } finally {
1076 RxJavaPlugins.reset();
1077 }
1078 }
1079
1080 @Test
1081 public void onCompleteOnErrorRace() {
1082 for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
1083
1084 List<Throwable> errors = TestHelper.trackPluginErrors();
1085 try {
1086 TestObserverEx<Integer> to = new TestObserverEx<>();
1087
1088 final SerializedObserver<Integer> so = new SerializedObserver<>(to);
1089
1090 Disposable d = Disposable.empty();
1091
1092 so.onSubscribe(d);
1093
1094 final Throwable ex = new TestException();
1095
1096 Runnable r1 = new Runnable() {
1097 @Override
1098 public void run() {
1099 so.onError(ex);
1100 }
1101 };
1102
1103 Runnable r2 = new Runnable() {
1104 @Override
1105 public void run() {
1106 so.onComplete();
1107 }
1108 };
1109
1110 TestHelper.race(r1, r2);
1111
1112 to.awaitDone(5, TimeUnit.SECONDS);
1113
1114 if (to.completions() != 0) {
1115 to.assertResult();
1116 } else {
1117 to.assertFailure(TestException.class).assertError(ex);
1118 }
1119
1120 for (Throwable e : errors) {
1121 assertTrue(e.toString(), e.getCause() instanceof TestException);
1122 }
1123 } finally {
1124 RxJavaPlugins.reset();
1125 }
1126 }
1127
1128 }
1129
1130 @Test
1131 public void nullOnNext() {
1132
1133 TestObserverEx<Integer> to = new TestObserverEx<>();
1134
1135 final SerializedObserver<Integer> so = new SerializedObserver<>(to);
1136
1137 Disposable d = Disposable.empty();
1138
1139 so.onSubscribe(d);
1140
1141 so.onNext(null);
1142
1143 to.assertFailureAndMessage(NullPointerException.class, ExceptionHelper.nullWarning("onNext called with a null value."));
1144 }
1145
1146 @Test
1147 @SuppressUndeliverable
1148 public void onErrorQueuedUp() {
1149 AtomicReference<SerializedObserver<Integer>> soRef = new AtomicReference<>();
1150 TestObserverEx<Integer> to = new TestObserverEx<Integer>() {
1151 @Override
1152 public void onNext(Integer t) {
1153 super.onNext(t);
1154 soRef.get().onNext(2);
1155 soRef.get().onError(new TestException());
1156 }
1157 };
1158
1159 final SerializedObserver<Integer> so = new SerializedObserver<>(to, true);
1160 soRef.set(so);
1161
1162 Disposable d = Disposable.empty();
1163
1164 so.onSubscribe(d);
1165
1166 so.onNext(1);
1167
1168 to.assertFailure(TestException.class, 1, 2);
1169 }
1170 }