AtomicInteger

GT-Sandbox-Snapshot: Example of 2 threads incrementing regular integer.

Code

package com.glassthought.sandbox

import gt.sandbox.util.output.Out
import kotlinx.coroutines.runBlocking
import kotlin.concurrent.thread

fun main() = runBlocking {
  val out = Out.standard() // Assuming Out.standard() is implemented elsewhere

  // Shared variable
  var counter = 0
  val iterations = 10000000

  // Threads
  val thread1 = thread {
    repeat(iterations) {
      counter++
    }
  }

  val thread2 = thread {
    repeat(iterations) {
      counter++
    }
  }

  // Wait for threads to finish
  thread1.join()
  thread2.join()

  // Display results
  val expected = iterations * 2
  out.infoGreen("Expected value: $expected actual value: $counter.")
  if (counter != expected) {
    out.infoRed("Counter is not equal to expected value, difference: ${expected - counter}")
  } else {
    out.infoGreen("Counter is equal to expected value")
  }
}

Command to reproduce:

gt.sandbox.checkout.commit fe555cbc09f9a3877ec9 \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run --quiet"

Recorded output of command:

[elapsed:   29ms][🥇/tname:main/tid:1][coroutine:unnamed] Expected value: 20000000 actual value: 19138589.
[elapsed:   42ms][🥇/tname:main/tid:1][coroutine:unnamed] Counter is not equal to expected value, difference: 861411
GT-Sandbox-Snapshot: AtomicInteger Works as expected counter is properly counted from 2 threads.

Code

package com.glassthought.sandbox

import gt.sandbox.util.output.Out
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicInteger
import kotlin.concurrent.thread

fun main() = runBlocking {
  val out = Out.standard() // Assuming Out.standard() is implemented elsewhere

  // Shared variable
  val counter = AtomicInteger(0)
  val iterations = 10000000

  // Threads
  val thread1 = thread {
    repeat(iterations) {
      counter.incrementAndGet()
    }
  }

  val thread2 = thread {
    repeat(iterations) {
      counter.incrementAndGet()
    }
  }

  // Wait for threads to finish
  thread1.join()
  thread2.join()

  // Display results
  val expected = iterations * 2
  val finalValue = counter.get()
  out.infoGreen("Expected value: $expected actual value: $finalValue.")
  if (finalValue != expected) {
    out.infoRed("Counter is not equal to expected value, difference: ${expected - finalValue}")
  } else {
    out.infoGreen("Counter is equal to expected value")
  }
}

Command to reproduce:

gt.sandbox.checkout.commit 82bcecd6e964af20b0ba \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run --quiet"

Recorded output of command:

[elapsed:  305ms][🥇/tname:main/tid:1][coroutine:unnamed] Expected value: 20000000 actual value: 20000000.
[elapsed:  316ms][🥇/tname:main/tid:1][coroutine:unnamed] Counter is equal to expected value