https://kotlinlang.org logo
#coroutines
Title
# coroutines
n

napperley

12/24/2017, 10:31 PM
If threads were used instead then all CPU cores would be maxed out and memory usage would spiral out of control, which would lead to the dreaded OOM (Out Of Memory error) scenario.
l

louiscad

12/24/2017, 10:33 PM
@napperley Your snippet doesn't use coroutines and doesn't use threads other than the main thread. It doesn't seem you understood coroutines. Did you take a look at the guide on GitHub? https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md
n

napperley

12/24/2017, 10:47 PM
Had a look through the Coroutines guide but didn't find anything covering event loops, and continuously running services.
The code snippet does use Kotlin Coroutines and kotlinx.coroutines library. Could have included the imports to make it more obvious that coroutines were being used.
l

louiscad

12/25/2017, 12:23 AM
You're only using the less coroutine-y part of the library:
runBlocking { … }
, which only allows to keep the calling thread active while the coroutine inside it's lambda are run, but there's no suspending code inside, so as Ken Yee said, yes, your CPU usage will be high until the print statements are executed. Did you understand the purpose of coroutines?
s

snrostov

12/25/2017, 12:23 AM
@napperley For example you can put
delay(100)
at the end of
printMessage
This will cause “non-blocking” (asynchronous) sleep
if you want to create new corutine at every iteration, you should put
runAsync
inside loop
Take a look to this example from docs:
Copy code
fun main(args: Array<String>) = runBlocking<Unit> {
    val jobs = List(100_000) { // launch a lot of coroutines and list their jobs
        launch {
            delay(1000L)
            print(".")
        }
    }
    jobs.forEach { it.join() } // wait for all jobs to complete
}
n

napperley

12/26/2017, 9:53 PM
The service has to run indefinitely (until it is cancelled). Each coroutine in the service doesn't need to run in a predefined order (no need for runAsync).
5 Views