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

doodla

11/18/2020, 8:18 PM
Given a block -
Copy code
var x: Int = 0

suspend fun modifyX() {
    if (x > 10) {
        x -= 1
    } else {
        x += 1
    }
}

fun main() {
    runBlocking {
        withContext(<http://Dispatchers.IO|Dispatchers.IO>){
            repeat(10) {
                modifyX()
            }
        }
    }
}
Does
x
need to be
@Volatile
?
z

Zach Klippenstein (he/him) [MOD]

11/18/2020, 8:19 PM
This code is fully synchronous, let alone multi-threaded, so no. There’s also no reason to use coroutines for this.
d

doodla

11/18/2020, 8:20 PM
Bad example then. I have a
suspend
function modifying an integer variable. Should this variable be synchronized?
It’s being read in another suspend function.
z

Zach Klippenstein (he/him) [MOD]

11/18/2020, 8:52 PM
Suspendability doesn’t matter for volatility, threading does. Suspension, and coroutines in general, doesn’t necessarily imply multiple threads. Although i think that because the coroutine threading machinery uses atomics, the JVM might guarantee that memory is synchronized correctly between multiple threads here even without volatile.
d

doodla

11/18/2020, 9:44 PM
@Zach Klippenstein (he/him) [MOD] Thanks for your time 🙏. I modified my example to better represent my question.
z

Zach Klippenstein (he/him) [MOD]

11/18/2020, 9:48 PM
Still doesn’t involve any concurrent access to that variable or parallel execution.
d

doodla

11/18/2020, 9:48 PM
Thank you!
3 Views