Search code examples
kotlinkotlinx.coroutines

Does kotlin coroutines block a thread on IO until it is finished?


From what I understand, a coroutine that does blocking IO will block the thread it is running on. The thread will be suspended by the OS to be rescheduled at a later point.

Does that mean that if I have a threadpool with 50 threads and 50 concurrent coroutines doing IO on each of the threads, they will effectively block all the threads in the threadpool until at least one of them has finished the IO-operation?

Or is there a mechanism to park the coroutines that has caused the blocking IO on some queue of some kind?


Solution

  • if I have a threadpool with 50 threads and 50 concurrent coroutines doing IO on each of the threads, they will effectively block all the threads in the threadpool until at least one of them has finished the IO-operation?

    Yes. There is no way around the fact that a blocking method blocks the calling thread. Coroutines aren't a magic wand that changes this.

    The value of the coroutine is that you can offload the blocking operation from the UI thread to a threadpool by using a very natural programming model. The code looks just like a normal function call that completes with a return value, but actually the coroutine suspends so that other UI event handlers can run.

    However, coroutines truly shine when working against a non-blocking, async API based on callbacks. In that case you can get behavior that can be described as "single-threaded concurrency" on the UI thread. Concurrency works by interleaving the execution of event handlers. The key difference to native threads is that the interleaving doesn't rely on pre-emptively suspending threads without their knowledge. Instead the coroutine must itself ask to be suspended.