compareAndExchange

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

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

Comparison of values is done by reference.

Since Kotlin

2.1

Samples

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

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

// Current value "bbb" is not equal to the expected value "aaa" ->
// compareAndExchange fails, does not store the new value and returns the current value "bbb".
println(a.compareAndExchange("aaa", "kkk")) // bbb
println(a.load()) // bbb 
   //sampleEnd
}
actual fun compareAndExchange(expectedValue: T, newValue: T): T(source)

Atomically stores the given new value into this AtomicReference 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: T, newValue: T): T(source)

Atomically stores the given new value into this AtomicReference 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.AtomicReference.compareAndSet, since java.util.concurrent.atomic.AtomicReference.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.AtomicReference.compareAndExchange for users running JDK 9 or higher.

Since Kotlin

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

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

Comparison of values is done by reference.

Since Kotlin

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

Atomically stores the given new value into this AtomicReference 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: T, newValue: T): T(source)

Atomically stores the given new value into this AtomicReference 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