Given a block - ```var x: Int = 0 suspend fun mo...
# coroutines
d
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
This code is fully synchronous, let alone multi-threaded, so no. There’s also no reason to use coroutines for this.
d
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
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
@Zach Klippenstein (he/him) [MOD] Thanks for your time 🙏. I modified my example to better represent my question.
z
Still doesn’t involve any concurrent access to that variable or parallel execution.
d
Thank you!