/
AtomicReference.kt
32 lines (23 loc) 路 1.03 KB
/
AtomicReference.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
31
32
package com.mirego.trikot.foundation.concurrent
class AtomicReference<T>(value: T) {
private val atomicValue = kotlinx.atomicfu.atomic(value)
val value: T get() = atomicValue.value
fun compareAndSet(expected: T, new: T): Boolean = atomicValue.compareAndSet(expected, new)
fun setOrThrow(expected: T, new: T) = setOrThrow(expected, new, null)
fun setOrThrow(expected: T, new: T, debugInfo: (() -> String)?) {
if (!compareAndSet(expected, new)) {
throw ConcurrentModificationException(
"($this) Unable to set $new to AtomicReference. " +
"Possible Race Condition. Expected value $expected was $value. " +
debugInfo?.let { "\n${it()}" }.orEmpty()
)
}
}
fun compareAndSwap(expected: T, new: T): T {
return if (compareAndSet(expected, new)) new else value
}
fun getAndSet(new: T): T {
return atomicValue.getAndSet(new)
}
}
fun <T> AtomicReference<T>.setOrThrow(new: T) = setOrThrow(value, new)