I saw this example in one of <@U2E974ELT>’s articl...
# coroutines
g
I saw this example in one of @elizarov’s articles https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761, about making CPU intensive call non-blocking. My doubt is as long as the work cannot be broken, this piece of code may not block main thread, but how can the Dispatcher make use of all cores on the system? Won't this just run on single background thread?
Copy code
suspend fun findBigPrime(): BigInteger =
    withContext(Dispatchers.Default) {
        BigInteger.probablePrime(4096, Random())
    }
b
but how can the Dispatcher make use of all cores on the system?
Should it? Non-blocking != parallel
Won't this just run on single background thread?
yes.
g
Thanks @bezrukov, then why use
Dispatchers.Default
for this case instead of a thread? Is there any difference I'm missing?
b
Dispatchers are backed by threads, and coroutines are designed to work with dispatchers instead of threads. How would you use raw thread here? findBigPrime returns result, so you can't simply make it
Copy code
suspend fun fidBigPrime(): BigInteger = Thread { ... }.start()
z
The default dispatcher does use threads. If you have a CPU-bound task, then some CPU core is gonna be required to execute it, whether it's running on a dedicated thread or a thread from a pool (like in the default dispatcher case). If you already have a thread pool, it's generally better to use it instead of creating one-off threads - threads are expensive.
g
I see, so that background thread would obviously be blocked right? So if I get enough requests, could that block all threads in the pool?
z
Yep