compareAndExchange

expect fun compareAndExchange(expectedValue: Int, newValue: Int): Int(source)

Atomically stores the given new value into this AtomicInt if the current value equals the expected value and returns the old value in any case.

Comparison of values is done by value.

Since Kotlin

2.1

Samples

import kotlin.concurrent.atomics.*
import kotlin.concurrent.thread

fun main() { 
   //sampleStart 
   val a = AtomicInt(7)
// Current value 7 is equal to the expected value 7 ->
// compareAndExchange succeeds, stores the new value 10 and returns the old value 7.
println(a.compareAndExchange(7, 10)) // 7
println(a.load()) // 10

// Current value 10 is not equal to the expected value 2 ->
// compareAndExchange fails, does not store the new value and returns the current value 10.
println(a.compareAndExchange(2, 12)) // 10
println(a.load()) // 10 
   //sampleEnd
}
actual fun compareAndExchange(expectedValue: Int, newValue: Int): Int(source)

Atomically stores the given new value into this AtomicInt. if the current value equals the expected value and returns the old value in any case.

Comparison of values is done by value.

Since Kotlin

2.1
actual fun compareAndExchange(expectedValue: Int, newValue: Int): Int(source)

Atomically stores the given new value into this AtomicInt if the current value equals the expected value and returns the old value in any case.

Comparison of values is done by value.

In order to maintain compatibility with Java 8, compareAndExchange is implemented using java.util.concurrent.atomic.AtomicInteger.compareAndSet, since java.util.concurrent.atomic.AtomicInteger.compareAndExchange method is only available starting from Java 9.

In the future releases it's planned to delegate the implementation of compareAndExchange to java.util.concurrent.atomic.AtomicInteger.compareAndExchange for users running JDK 9 or higher.

Since Kotlin

2.1
actual fun compareAndExchange(expectedValue: Int, newValue: Int): Int(source)

Atomically stores the given new value into this AtomicInt if the current value equals the expected value and returns the old value in any case.

Comparison of values is done by value.

Since Kotlin

2.1
actual fun compareAndExchange(expectedValue: Int, newValue: Int): Int(source)

Atomically stores the given new value into this AtomicInt if the current value equals the expected value and returns the old value in any case.

Comparison of values is done by value.

Since Kotlin

2.1
actual fun compareAndExchange(expectedValue: Int, newValue: Int): Int(source)

Atomically stores the given new value into this AtomicInt if the current value equals the expected value and returns the old value in any case.

Comparison of values is done by value.

Since Kotlin

2.1