Woops <https://kotlinlang.org/docs/shared-mutable-...
# coroutines
r
Woops https://kotlinlang.org/docs/shared-mutable-state-and-concurrency.html#the-problem There is an issue in the documentation, but I don't understand why
😅 1
😂 1
This works differently somehow
runBlocking
documentation states:
Copy code
The default CoroutineDispatcher for this builder is an internal implementation of event loop that processes continuations in this blocked thread until the completion of this coroutine. See CoroutineDispatcher for the other implementations that are provided by kotlinx.coroutines.
Does that mean
withContext(Dispatchers.Default)
gets ignored or something? I just don't get what's happening.
s
No,
withContext(Dispatchers.Default)
doesn't get ignored.
runBlocking
starts out using its event loop dispatcher, but inside the
withContext
block, the default dispatcher will be used.
Are you asking why the code prints
Counter = 100000
despite the doc saying that's "highly unlikely"?
b
it is unlikely to print 100k but not impossible. Especially in a constrained environment - where for example only a single CPU core is dedicated to the execution
1
s
It will be more unlikely when running with more available CPUs on a less busy system. Each Kotlin playground instance seems to have 2 available cores and they might well be shared with other stuff.
You'll probably get very different results on your own machine
r
Oh I thought it was 100% 100k because it returned 100k five times in a row for me.
That's pretty far from highly unlikely to be honest
👍 1
b
it highly depends on the environment and task size. They selected a bad example. With k=1000 repeat(1000) { counter++ } is almost instant. They should be selecting 10k or 100k (with probably reducing N) The smaller task will lead to faster execution and higher chance of a single thread from Dispatchers.Default will wake up and pick all the tasks sequentially (just because the thread spawn also takes time)
a