-
Notifications
You must be signed in to change notification settings - Fork 448
/
AtomicLong.kt
66 lines (55 loc) · 1.55 KB
/
AtomicLong.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package arrow.atomic
public expect class AtomicLong(initialValue: Long) {
public fun get(): Long
public fun set(newValue: Long)
public fun getAndSet(value: Long): Long
public fun incrementAndGet(): Long
public fun decrementAndGet(): Long
public fun addAndGet(delta: Long): Long
public fun compareAndSet(expected: Long, new: Long): Boolean
}
public var AtomicLong.value: Long
get() = get()
set(value) {
set(value)
}
/**
* Infinite loop that reads this atomic variable and performs the specified [action] on its value.
*/
public inline fun AtomicLong.loop(action: (Long) -> Unit): Nothing {
while (true) {
action(value)
}
}
public fun AtomicLong.tryUpdate(function: (Long) -> Long): Boolean {
val cur = value
val upd = function(cur)
return compareAndSet(cur, upd)
}
public inline fun AtomicLong.update(function: (Long) -> Long) {
while (true) {
val cur = value
val upd = function(cur)
if (compareAndSet(cur, upd)) return
}
}
/**
* Updates variable atomically using the specified [function] of its value and returns its old value.
*/
public inline fun AtomicLong.getAndUpdate(function: (Long) -> Long): Long {
while (true) {
val cur = value
val upd = function(cur)
if (compareAndSet(cur, upd)) return cur
}
}
/**
* Updates variable atomically using the specified [function] of its value and returns its new value.
*/
public inline fun AtomicLong.updateAndGet(function: (Long) -> Long): Long {
while (true) {
val cur = value
val upd = function(cur)
if (compareAndSet(cur, upd)) return upd
}
}