Sobes.tech
Junior — Middle

How can you ensure the consistency of variable updates when multiple coroutines operate simultaneously?

sobes.tech AI

Answer from AI

To ensure consistent updating of a variable when multiple coroutines operate simultaneously in Android (Kotlin), synchronization mechanisms such as:

  • Mutex from kotlinx.coroutines — allows blocking a critical section of code so that only one coroutine can modify the variable at a time.
  • Atomic variables from the java.util.concurrent.atomic package — provide atomic operations without locks.

Example using Mutex:

import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

val mutex = Mutex()
var sharedCounter = 0

suspend fun increment() {
    mutex.withLock {
        sharedCounter++
    }
}

fun main() = runBlocking {
    val jobs = List(1000) {
        launch {
            increment()
        }
    }
    jobs.forEach { it.join() }
    println("Counter = $sharedCounter")
}

This approach guarantees that the value of sharedCounter will be updated correctly without data races.

How can you ensure the consistency of variable… - sobes.tech