Reputation: 8135
Why they are used for different kinds of task? What make them different when handling computational task vs io task ?
Schedulers.computation( ) - meant for computational work such as event-loops and callback processing; do not use this scheduler for I/O (use Schedulers.io( ) instead); the number of threads, by default, is equal to the number of processors
Schedulers.io( ) - meant for I/O-bound work such as asynchronous performance of blocking I/O, this scheduler is backed by a thread-pool that will grow as needed; for ordinary computational work, switch to Schedulers.computation( ); Schedulers.io( ) by default is a CachedThreadScheduler, which is something like a new thread scheduler with thread caching
Upvotes: 3
Views: 1093
Reputation: 1076
The most important point is that both Schedulers.io and Schedulers.computation are backed by unbounded auto-reclaiming thread pools. This characteristic is only shared by the Schedulers.from(Executor) in the case the Executor is created with newCachedThreadPool (unbounded with an auto-reclaim thread pool).
Schedulers.computation is, by default, configured with a number of threads equal to the number of available CPUs, so computations are performed as fast as it can. You can increase this number but that might introduce thread switching overhead and slow down the computations.
As for Schedulers.io, you should use it only for blocking I/O operations since they would block the calling thread. Do not use it if your I/O call is made through an asynchronous or reactive API as there is no mechanism to call the call back on Scheduler.io.
That being said, an important role for these Schedulers is to provide a multi-threaded context to a flatMap() operator, enabling concurrency at the core of a reactive stream.
Find more details from similar question here and articles on RxJava2 Schedulers and Concurrency where you can find detailed explanations and code samples.
Hope this helps,
Softjake
Upvotes: 1
Reputation: 3502
I/O and Computation are very different workloads.
Computation is purely CPU-bound, so you want to limit the number of threads so that they don't fight over the CPU and starve themselves. If you have 1000 threads all trying to do work on 8 cores, you're probably going to have a bad time. Schedulers.computation() is capped to the number of cores.
I/O is different, since while they typically need a thread for maintaining context, they don't really use the CPU - they just sleep until the I/O is done. It's perfectly fine to have 1000 I/O operations on a single-core machine, since they're all asleep the majority of the time. Schedulers.io() is uncapped, and will spawn as many threads as necessary
Upvotes: 11