Home > Mobile >  Compare and swap value in atomic integer kotlin
Compare and swap value in atomic integer kotlin

Time:02-20

Hey I am learning atomic integer in kotlin. I want to know is there atomic integer swap value if current value is smaller than new value. For example

AtomicInt 10

Scenario 1 new value is 5 and it changes to 5 because 5 is lower than 10

Scenario 2 new value is 20 it will not change the atomic value because 20 is greater than 10.

Can we do this throught enter image description here

CodePudding user response:

Sure. The following is a compareAndSet version, which I think is what you want, but it's easy enough to change it to compareAndSet:

fun AtomicInt.compareAndSetIfLess(newValue: Int): Boolean {
  do {
    val oldValue = value
    if (newValue > oldValue) {
      return false
    }
  } while (!compareAndSet(oldValue, newValue))
  return true
}
  • Related