-
Notifications
You must be signed in to change notification settings - Fork 451
/
Copy pathAtomicRef.kt
30 lines (25 loc) · 918 Bytes
/
AtomicRef.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package arrow.core.continuations
import kotlin.concurrent.AtomicReference
import kotlin.native.concurrent.freeze
import kotlin.native.concurrent.isFrozen
public actual class AtomicRef<V> actual constructor(initialValue: V) {
private val atom = AtomicReference(initialValue.freeze())
public actual fun get(): V = atom.value
public actual fun set(value: V) {
atom.value = value.freeze()
}
public actual fun getAndSet(value: V): V {
if (atom.isFrozen) value.freeze()
while (true) {
val cur = atom.value
if (cur === value) return cur
if (atom.compareAndExchange(cur, value) === cur) return cur
}
}
/**
* Compare current value with expected and set to new if they're the same. Note, 'compare' is checking
* the actual object id, not 'equals'.
*/
public actual fun compareAndSet(expected: V, new: V): Boolean =
atom.compareAndSet(expected, new.freeze())
}