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

Viktor Qvarfordt

05/13/2019, 11:06 PM
I’m trying to set up a minimal example that gives race conditions. Any suggestions? The best I’ve got is this https://pl.kotl.in/4yU_BS_qv but it has a quirk that I don’t understand. (Question embedded in the code snippet).
b

bdawg.io

05/13/2019, 11:15 PM
Because
GlobalScope
is not the same as the scope provided by
runBlocking
. Your
runBlocking
parent scope only has the main thread, so only one coroutine will run at a time accessing the
counter
from the same thread, so there's no shared mutable state going on.
GlobalScope
, on the other-hand, has multiple threads available to it, which means multiple of your `massiveRun`'s job will run in parallel, causing overwriting of mutable state
You would want to do
Copy code
runBlocking {
    launch(Dispatchers.Default) {
        // paste the function body
    }.join()
}
v

Viktor Qvarfordt

05/13/2019, 11:17 PM
Excellent explanation! Thank you.
b

bdawg.io

05/13/2019, 11:18 PM
Immediately joining on a job you created with launch is generally a code smell that can be replaced with
Copy code
runBlocking {
    withContext(Dispatchers.Default) {
        // paste the function body
    }
}
🙏 1
happy to help! 🎉
v

Viktor Qvarfordt

05/13/2019, 11:20 PM
Awesome, that’s a great tip! Based on your answer I also found this in the documentation (for anyone reading this that wants more): https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html
l

louiscad

05/14/2019, 5:51 AM
Why not just use
suspend fun main(): Unit = coroutineScope { … }
? It uses
Dispatchers.Default
.
👍 2
🤔 1
b

bdawg.io

05/14/2019, 4:40 PM
That's good to know @louiscad! I would say it's a bit harder to know when reading the code though without background knowledge
l

louiscad

05/14/2019, 4:46 PM
Here's a little part of my background @bdawg.io: The first time I noticed it was during my first English talk (I'm French native, we are renowned for our foreign languages skill 😅), when my demo using 2 concurrent
Thread.sleep
failed to show any difference with `delay`… It was the first I used it as it was new in 1.3RC. I natively thought it'd be like
runBlocking
. Found the answer and fixed it during Q&A, fortunately.
4 Views