From d5ed25cb54e2d2d899ccf98f0751984d4336ce16 Mon Sep 17 00:00:00 2001 From: Andrew Golovashevich Date: Wed, 26 Mar 2025 19:01:54 +0300 Subject: [PATCH] Avoiding double access to field in 'compareAndExchange' inline implementation --- .../utility/reference_counter/_AtomicLong.kt | 19 ++++++++++++------- .../utility/reference_counter/_AtomicLong.kt | 10 ++++++---- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/jvmMain/kotlin/ru/landrafhomyak/utility/reference_counter/_AtomicLong.kt b/src/jvmMain/kotlin/ru/landrafhomyak/utility/reference_counter/_AtomicLong.kt index d5c99c8..5771462 100644 --- a/src/jvmMain/kotlin/ru/landrafhomyak/utility/reference_counter/_AtomicLong.kt +++ b/src/jvmMain/kotlin/ru/landrafhomyak/utility/reference_counter/_AtomicLong.kt @@ -30,13 +30,18 @@ internal actual /*value*/ class _AtomicLong { actual fun compareAndSet(expected: Long, newValue: Long): Boolean = this._native.compareAndSet(expected, newValue) - actual fun compareAndExchange(expected: Long, newValue: Long): Long = - if (_Linkage._isNativeCompareAndExchangeExists) this._native.compareAndExchange(expected, newValue) - else _Misc._compareAndExchange( - get = this._native::get, - cas = this._native::compareAndSet, - expected = expected, newValue = newValue - ) + actual fun compareAndExchange(expected: Long, newValue: Long): Long { + if (_Linkage._isNativeCompareAndExchangeExists) { + return this._native.compareAndExchange(expected, newValue) + } else { + val a = this._native + return _Misc._compareAndExchange( + get = a::get, + cas = a::compareAndSet, + expected = expected, newValue = newValue + ) + } + } private object _Linkage { @JvmField diff --git a/src/nonJvmMain/kotlin/ru/landrafhomyak/utility/reference_counter/_AtomicLong.kt b/src/nonJvmMain/kotlin/ru/landrafhomyak/utility/reference_counter/_AtomicLong.kt index 466ce68..9825bca 100644 --- a/src/nonJvmMain/kotlin/ru/landrafhomyak/utility/reference_counter/_AtomicLong.kt +++ b/src/nonJvmMain/kotlin/ru/landrafhomyak/utility/reference_counter/_AtomicLong.kt @@ -24,10 +24,12 @@ internal actual class _AtomicLong { actual fun compareAndSet(expected: Long, newValue: Long): Boolean = this._atomicfu.compareAndSet(expected, newValue) - actual fun compareAndExchange(expected: Long, newValue: Long): Long = - _Misc._compareAndExchange( - get = this._atomicfu::value::get, - cas = this._atomicfu::compareAndSet, + actual fun compareAndExchange(expected: Long, newValue: Long): Long { + val a = this._atomicfu + return _Misc._compareAndExchange( + get = a::value::get, + cas = a::compareAndSet, expected = expected, newValue = newValue ) + } } \ No newline at end of file