Stately icon indicating copy to clipboard operation
Stately copied to clipboard

Add getAndUpdate() method to AtomicReference

Open volo-droid opened this issue 2 years ago • 0 comments

On JVM the AtomicReference class contains the getAndUpdate() method. It'd be convenient to have it for other targets/common code as well. The non-JVM implementation can look like:

fun getAndUpdate(updateFunction: (V) -> V): V {
    while(true) {
        val prev = get()
        val next = updateFunction(prev)
        if (compareAndSet(prev, next)) return prev
    }
}

The signature of the corresponding JVM method is:

public final V getAndUpdate(UnaryOperator<V> updateFunction)

where UnaryOperator is a functional interface:

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T>

That should place nicely with the SAM conversion

volo-droid avatar Feb 21 '23 15:02 volo-droid