javakotlinatomicinteger

Compare and swap value in atomic integer kotlin


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 CompareAndSwap function?

UPDATE after @LouisWasserman suggestion

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

I am getting error on Unresolved reference: AtomicInt

enter image description here


Solution

  • 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
    }