Can someone please help me with a sensible close t...
# coroutines
g
Can someone please help me with a sensible close to real-world usecase/example, where Coroutines are better than ExecutorService (say with pool count = no.of cores), for NON-blocking operations? (without using
delay()
)
r
delay
is non-blocking, and that is perhaps your answer right there...
g
ya all examples are filled with only
delay
which I might not ever use in real app, so wondering what other non-blocking operations can a coroutine is handy over threads?
r
For
delay
substitute any operation that might take some time to perform. With coroutines, such calls are non-blocking (i.e. they don't block a thread), but at the same time (from your program's perspective), synchronous.
A network call is a good example.
g
But a network call is a blocking call, which blocks the thread the coroutine runs on
🚫 2
r
Not necessarily. You can make the call using a non-blocking facility like java.nio, either directly or via a multitude of libraries that use it under the hood -- netty, ktor, apache httpclient, etc.
g
So if the thread is not blocked, who does notifies the app when the data is available from the network?
r
This isn't coroutines specific... go read up on java.nio. Look up selectors. This is all well supported by modern operating systems and JVMs.
g
sure thanks @rocketraman
so I believe you need a reactive server or java.nio to actually get the benifits of coroutines with non-blocking calls right?
r
Network calls are one example, presented in that doc above more generally as "Asynchronous computations" -- for example, anywhere you have a traditional JVM function with a callback parameter, or are using message passing, or really any style of async computation. There are also use cases that don't require asynchronicity. Lookup the generators use case in that doc. Recently Roman posted an article about using the coroutine machinery to implement non-tail recursive functions without worrying about stack overflows: https://medium.com/@elizarov/deep-recursion-with-coroutines-7c53e15993e3.
(BTW, that's now in the 1.4 stdlib as an experimental facility: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-deep-recursive-function/)
g
Grt! I shall explore that 🙂
g
One more reason is that thread is heavo abstraction, it's fine to consume one per number of cpus, but even a few hundreds of threads is a problem, this why usage of non-blocking api scales a lot a better, for everything, network, database, io And as was said, it's better to compare coroutines with callbacks, this the case where they shine, not with thread executor, difference in some cases (for example executing a heavy operations on all cares) is really similar with coroutines and executor, just better api in case of coroutines (mostly because of structured concurrency)