I am running some very simple code based on the kotlin coroutine examples at https://kotlinlang.org/docs/tutorials/coroutines/coroutines-basic-jvm.html
Kotlin coroutine sum numbers properly up to a point and then fail. It works on summing 1…10,000 but fails on 1…100,000 and above. The sample code page says for summing 1…1,000,000: " Now it prints something sensible: 1784293664
, because all coroutines complete."
But that is very wrong.
1 to 1,000,000 is:
499,999 * 1,000,000 + 500,000 + 1,000,000 = 500,000,500,000
My environment is Intellij on a Mac running openjdk (jdk-12.0.2.jdk) and kotlin plugin 1.3.41-release-IJ2019.2-1 with the kotlinx-coroutines-core-1.1.1.jar. I am producing java 12 bytecode and using the kotlin 1.3 compiler.
Code below outputs:
Sum 1…1,000,000 (this kotlin coroutine answer is wrong): 1784293664
simple loop method 1…1,000,000 (correct answer)= 500000500000
So what is going wrong? I am new to kotlin and so wonder if I have made an error.
Here is the code:
package unleashbts
import kotlinx.coroutines.*
import java.util.concurrent.atomic.AtomicLong
fun main() {
val deferred = (1..1_000_000).map { n ->
GlobalScope.async {
n
}
}
runBlocking {
val sum = deferred.sumBy { it.await() }
println("Sum 1..1,000,000 (this kotlin coroutine answer is wrong): $sum")
}
//alternative for loop
val d = AtomicLong()
for (j in 1..1_000_000L)
{
d.addAndGet(j)
}
println("simple loop method 1..1,000,000 (correct answer)= ${d.get()}")
}