📌 It depends on the Scheduler you use.
✅ Schedulers.io()
- Purpose: For I/O-bound tasks like DB calls, file access, HTTP calls.
- Type: Cached thread pool (like Java’s
Executors.newCachedThreadPool()). - Threads: Unbounded (new threads created as needed, idle ones reused).
- Good for: Many short, non-blocking, I/O operations.
⚠️ Careful! Too many blocking operations might spawn tons of threads and exhaust resources.
✅ Schedulers.computation()
- Purpose: For CPU-bound tasks like data processing, math, game loops.
- Type: Fixed thread pool
- Threads: Equal to the number of CPU cores (
Runtime.getRuntime().availableProcessors()) - Good for: CPU-intensive work (not blocking I/O!)
✅ Schedulers.single()
- Purpose: Sequential tasks in a single thread.
- Threads: One (shared across all Rx chains that use this).
- Good for: Serialized processing, shared logging.
✅ Schedulers.newThread()
- Purpose: Every call creates a new thread.
- Threads: Unlimited, but not reused.
- Good for: Rare cases, like isolated blocking operations.
⚠️ Be cautious: This can easily cause thread leaks.
🛠️ Can You Create Your Own Threads?
Yes! You can create a custom Scheduler using:
Scheduler myScheduler = Schedulers.from(Executors.newFixedThreadPool(4));
Or use any Java ExecutorService:
ExecutorService executor = Executors.newFixedThreadPool(2);
Scheduler custom = Schedulers.from(executor);
Then use it like:
.observeOn(custom)
.subscribe(...);
🔥 Why make your own?
- Control how many threads are used.
- Handle priority, naming, or lifecycle.
- Useful when mixing RxJava with other systems (like Spring or Akka).
🧪 Recap Table:
| Scheduler | Thread Pool | Thread Count | Best For |
|---|---|---|---|
Schedulers.io() | Cached | Unbounded | Network / file / DB access |
Schedulers.computation() | Fixed | CPU cores (e.g. 8) | Math, parsing, CPU-bound work |
Schedulers.single() | Single-threaded | 1 | Sequential tasks |
Schedulers.newThread() | New per call | Unbounded | Short-lived isolated work |
Schedulers.from(...) | Custom executor | You decide | Full control |