arrow icon indicating copy to clipboard operation
arrow copied to clipboard

Update arrow.atomics to base on kotlin stdlib common atomics

Open revonateB0T opened this issue 9 months ago • 3 comments

https://github.com/Kotlin/KEEP/issues/398

revonateB0T avatar Mar 21 '25 03:03 revonateB0T

Just remove platform implementations and keep extension functions?

e.g.

import kotlin.concurrent.atomics.AtomicInt
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract

inline fun AtomicInt.loop(action: (Int) -> Unit): Nothing {
    contract { callsInPlace(action, InvocationKind.AT_LEAST_ONCE) }
    do {
        action(load())
    } while (true)
}

inline fun <R> AtomicInt.update(function: (Int) -> Int, transform: (old: Int, new: Int) -> R): R {
    contract {
        callsInPlace(function, InvocationKind.AT_LEAST_ONCE)
        callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
    }
    loop { cur ->
        val upd = function(load())
        if (compareAndSet(cur, upd)) return transform(cur, upd)
    }
}

inline fun AtomicInt.updateAndGet(function: (Int) -> Int): Int {
    contract { callsInPlace(function, InvocationKind.AT_LEAST_ONCE) }
    return update(function) { _, new -> new }
}

revonateB0T avatar Mar 21 '25 03:03 revonateB0T

@serras Btw any possibility to upstream these extension functions to kotlin stdlib?

revonateB0T avatar Mar 21 '25 03:03 revonateB0T

@revonateB0T I've reported this as an issue in YouTrack.

serras avatar Mar 29 '25 10:03 serras

We've decided to keep our implementation of atomics for the time being (until the new ones are no longer experimental). The update family of functions is showing in 2.2.20, so this is definitely a win, since you can now easily migrate from Arrow atomics into Kotlin ones.

serras avatar Jul 23 '25 19:07 serras