Race condition With Threads

package com.glassthought.sandbox

class RaceConditionInducer {
  private var value = 0

  
  // @Synchronized // would fix this example race condition.
  fun incrementValue() {
    val storedValue = value

    Thread.sleep(10)

    println("Incrementing value from storedValue=$storedValue to ${storedValue + 1}")
    value = storedValue + 1
  }

  fun getValue() = value
}

fun main() {
  val raceConditionInducer = RaceConditionInducer()

  val threads = (1..10).map {
    Thread { raceConditionInducer.incrementValue() }
  }
  threads.forEach { it.start() }
  threads.forEach { it.join() }

  println("Value: ${raceConditionInducer.getValue()}")
}

Command to reproduce:

gt.sandbox.checkout.commit 0b65495f3299ff186efc \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run"

Recorded output of command:

> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
> Task :app:processResources NO-SOURCE
> Task :app:compileKotlin
> Task :app:compileJava NO-SOURCE
> Task :app:classes UP-TO-DATE

> Task :app:run
Incrementing value from storedValue=0 to 1
Incrementing value from storedValue=0 to 1
Incrementing value from storedValue=0 to 1
Incrementing value from storedValue=0 to 1
Incrementing value from storedValue=0 to 1
Incrementing value from storedValue=0 to 1
Incrementing value from storedValue=0 to 1
Incrementing value from storedValue=0 to 1
Incrementing value from storedValue=0 to 1
Incrementing value from storedValue=0 to 1
Value: 1

BUILD SUCCESSFUL in 1s
2 actionable tasks: 2 executed

Backlinks