1

I have created a maven project in Intellij IDEA , I'm trying to execute the below simple rxjava code

Observable.just(1,2,3,4)
          .observeOn(Schedulers.io())
          .subscribe(new Consumer<Integer>() {
              @Override
              public void accept(Integer integer) throws Exception {
                  System.out.println(integer);
              }
         });

I expect the result 1 , 2 , 3 , 4 to be printed in the io thread. But when I run the code, it doesn't print anything. If I remove the observeOn(Schedulers.io) , then it prints as expected in the main thread. I created creating a custom Thread pool as shown below

Executor executor = Executors.newFixedThreadPool(1);
Observable.just(1,2,3,4)
    .observeOn(Schedulers.from(executor))
    .subscribe(new Consumer<Integer>() {
        @Override
        public void accept(Integer integer) throws Exception {
            System.out.println(integer);
        }
    });

This is working properly. The Schedulers.newThread() and Schedulers.computation() threads also working properly. Only Schedulers.io has no effect in the code. Why is that?

Below is my dependency for Rxjava

  <dependency>
        <groupId>io.reactivex.rxjava2</groupId>
        <artifactId>rxjava</artifactId>
        <version>2.2.4</version>
    </dependency>
Gayan Mettananda
  • 1,498
  • 14
  • 21
doe
  • 971
  • 2
  • 11
  • 27

1 Answers1

4

The RxJava Schedulers.io() schedulers use deamon threads.

A daemon thread is a thread that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.

source

In your first example, the main method finishes, and the program terminates so you don't see any output. Adding Thread.sleep() at the end of your main method will delay the exit and you should be able to see the output.

I assume Executors.newFixedThreadPool(1) doesn't use deamon threads, so it blocks the main method from exiting and you see different output.

LordRaydenMK
  • 13,074
  • 5
  • 50
  • 56
  • Hi, Thanks for the explanation. I have one more query. As you mentioned _**A daemon thread does not prevent the JVM from exiting when the program finishes but the thread is still running**_. So, the `Schedulers.io()` is still active even if the main thread has terminated. Then why doesn't it print the `System.out.println(integer);` in the `subscriber`? Is it because the `Consumer` anonymous class instance would be cleaned up by the GC? Wouldn't the `Consumer` class instance be holding by the `io` thread? Please correct me if I'm wrong. – doe Dec 09 '18 at 07:02
  • Okay, I got the answer. It seems _**If JVM finds running daemon thread, it terminates the thread and after that shutdown itself. JVM does not care whether Daemon thread is running or not.**_ – doe Dec 09 '18 at 07:34