Hi. Trying to dig into the docs & tutorials on...
# coroutines
f
Hi. Trying to dig into the docs & tutorials on https://kotlinlang.org/docs/coroutines-basic-jvm.html and https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/01_Introduction for the n-th time to try to get the grip on them 😉 The doc says that the following code will return an arbitrary number and I agree with it; we don’t wait for the coroutines to finish. However it does not for me - I’ve run it 20 times - each resulting in the sum being `500000500000`… (java 15, kotlin 1.4.31, coroutines 1.4.3, macOS) Any tips/insight as to why?
Copy code
package samples

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicLong

fun main() {
    val c = AtomicLong()
        for (i in 1..1_000_000L)
        GlobalScope.launch {
            c.addAndGet(i)
        }
        println(c.get())
}
PS! if this is better suited as question in #getting-started please tell me and I’ll move it there.
z
Just because it’s arbitrary doesn’t mean it necessarily will actually change on every run - just that it could. It’s possible your machine just happens to be scheduling threads the same way way for each run, especially if the load from other processes isn’t changing much between executions.
You could try using differently-sized thread pools instead of global scope
f
I’ve tried
GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>)
- which gives the behaviour
I understand it’s not guaranteed to return the right sum, but I find it strange not being able to reproduce it on my machine
cc: @elizarov - do you have any thoughts on this?
z
So both
Dispatchers.Default
and
<http://Dispatchers.IO|Dispatchers.IO>
give the same behavior? I’m surprised too
f
yes, they do
Running with Dispatchers.IO takes longer time consistently tough:
Copy code
fun main() {
    listOf(Dispatchers.Default, <http://Dispatchers.IO|Dispatchers.IO>).forEach { 
        println("time used: with $it: " + measureTimeMillis { test1(it) }) 
    }
}

private fun test1(dispatcher: CoroutineDispatcher) {
    val c = AtomicLong()
    for (i in 1..1_000_000L)
        GlobalScope.launch(dispatcher) {
            c.addAndGet(i)
        }
    println(c.get())
}
=>
Copy code
500000500000
time used: with Dispatchers.Default: 2753
500000500000
time used: with <http://Dispatchers.IO|Dispatchers.IO>: 6783