0

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

Kotlin Learner
  • 3,995
  • 6
  • 47
  • 127

1 Answers1

1

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
}
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • 1
    thanks for reply me. I want to know what is d/w [AtomicInteger](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html) and [AtomicInt](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.native.concurrent/-atomic-int/)? – Kotlin Learner Feb 19 '22 at 22:06
  • There's no real difference, they're just separately built for different platforms. Use https://github.com/Kotlin/kotlinx.atomicfu so you don't have to worry. – Louis Wasserman Feb 19 '22 at 22:08
  • I am trying to add the dependency but it giving error in my gradle file. Can you tell me which one I need to add in my gradle function? – Kotlin Learner Feb 19 '22 at 22:17
  • No, I can't. I don't use Gradle. – Louis Wasserman Feb 19 '22 at 23:13
  • Thanks @LouisWasserman. I downloaded from main source. Thanks a million ☺️ – Kotlin Learner Feb 19 '22 at 23:19