Hello if I have a server running on the cloud with...
# coroutines
k
Hello if I have a server running on the cloud with 1 cpu core per server instance ( so 1 thread at a time) does it make sense when wanting to run code concurrently to use
<http://Dispatchers.IO|Dispatchers.IO>
? As only 1 thread can run at a time. Would it be sufficient to just use
coroutineScope
and
async
directly ?
k
Unless you're using non-blocking io, no. You'll still want to use
<http://Dispatchers.IO|Dispatchers.IO>
. Threads which are blocked by IO will be parked by the OS until they can be resumed, which is why
<http://Dispatchers.IO|Dispatchers.IO>
can create and use more threads than the CPU supports.
k
Yes when using non blocking io. for example I have a non blocking io server which receives a request and then wants to concurrently call 10 diffenrent different endpoints
k
It depends how you're calling those 10 different endpoints. If you're using something blocking like Java's built in
HttpClient
then you'll want to use
<http://Dispatchers.IO|Dispatchers.IO>
. If you're using something that handles this for you, like Retrofit's suspending function, then you don't need to worry about dispatchers.
👍 2
k
Yes using non blocking code and clients so a single thread can handle concurrency as the suspension from the non blocking clients will allow the concurrent code to run
k
Practically speaking, that’s correct. It’s not 100% accurate though — even Retrofit will use a threadpool underneath and block threads on IO. It doesn’t matter though, the OS will handle scheduling the resumption of those threads. You can treat calls of Retrofit’s suspending functions or Ktor’s suspending function as functionally non-blocking for your use case.
👍 1