I have following code:
ExecutorService poolA = newFixedThreadPool(10, threadFactory("Sched-A-%d"));
Scheduler schedulerA = Schedulers.from(poolA);
ExecutorService poolB = newFixedThreadPool(10, threadFactory("Sched-B-%d"));
Scheduler schedulerB = Schedulers.from(poolB);
ExecutorService poolC = newFixedThreadPool(10, threadFactory("Sched-C-%d"));
Scheduler schedulerC = Schedulers.from(poolC);
private ThreadFactory threadFactory(String pattern) {
return new ThreadFactoryBuilder()
.setNameFormat(pattern).build();
}
@Test
public void testSubscribedOnObservedOn() {
log("Starting");
final Observable<String> obs = simple();
log("Created");
obs
.doOnNext(x -> log("Found 1: " + x))
.observeOn(schedulerB)
.doOnNext(x -> {Thread.sleep(100);log("Found 2: " + x);})
.observeOn(schedulerC)
.doOnNext(x -> log("Found 3: " + x))
.subscribeOn(schedulerA)
.subscribe(
x -> log("Got 1: " + x),
Throwable::printStackTrace,
() -> log("Completed")
);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log("Exiting");
}
Last 2 operators are to be run on schedulerC. I expect only one thread used for this. But output suggests 2.
0 | main | Starting
72 | main | Created
135 | Sched-A-0 | Subscribed
136 | Sched-A-0 | Found 1: A
138 | Sched-A-0 | Found 1: B
239 | Sched-B-0 | Found 2: A
239 | Sched-C-0 | Found 3: A
240 | Sched-C-0 | Got 1: A
341 | Sched-B-0 | Found 2: B
341 | Sched-C-1 | Found 3: B
341 | Sched-C-1 | Got 1: B
341 | Sched-C-1 | Completed
3129 | main | Exiting
Sched-C-0, Sched-C-1 are used. Is this behaviour correct?
question from:
https://stackoverflow.com/questions/65661579/rxjava-scheduler-using-more-threads-than-expected 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…