0

According to this question, Schedulers.io() will create an unbounded number of threads. In my application, this is an issue because I have hundreds of asynchonous tasks to complete.

The recommendation in the comments is to use Scheduler.from(Executors.newFixedThreadPool(n)), which is reasonable, but the usage pattern is different to Schedulers.io():

  • With Schedulers.io(), I can re-use the same thread-pool through-out my application, and Rx will properly call shutdown for me.
  • With Scheduler.from(Executors.newFixedThreadPool(n)), I have to make the Scheduler available across my application and remember to call shutdown.

Questions:

  • Can I just tweak the behaviour of Schedulers.io() to use a bounded thread-pool?
  • What is the recommended way to thread a Scheduler through-out an Rx application, and ensure that it is shutdown correctly?
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • Maybe [`Schedulers.computation()`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#computation()) is what you are looking for – Lamorak Jun 19 '17 at 20:50

1 Answers1

1

For RxJava, you can use RxJavaHooks.onIOScheduler to return your Scheduler as Schedulers.io. But you can't avoid IOScheduler be created.

For RxJava2, you can use RxJavaPlugins.setInitIoSchedulerHandler to init the IOScheduler by your Scheduler directly.

Dean Xu
  • 4,438
  • 1
  • 17
  • 44
  • Could you give an example of `setInitIoSchedulerHandler`? The API is not what I expected. – sdgfsdh Jun 20 '17 at 10:50
  • 1
    @sdgfsdh Use `RxJavaPlugins.setInitIoSchedulerHandler(c -> mySchedler);` to set `myScheduler` as `IOScheduler` before `Schedulers`'s initialization. – Dean Xu Jun 20 '17 at 14:18
  • What is `c`? Do I need to dispose of `myScheduler` later in my code? – sdgfsdh Jun 20 '17 at 14:31
  • @sdgfsdh If you see the code of `setInitIoSchedulerHandler`, you will not ask 'what is c'. You need to dispose your `myScheduler` later. If you want it dispose automatically, I have a solution on [link](https://github.com/XDean/Java-EX/blob/master/src/main/java/xdean/jex/extra/rx/RxUtil.java). `Executor` will dispose itself when the `Scheduler` be recycled. – Dean Xu Jun 20 '17 at 14:40