-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFAABasedQueueSimplified.kt
More file actions
37 lines (32 loc) · 986 Bytes
/
FAABasedQueueSimplified.kt
File metadata and controls
37 lines (32 loc) · 986 Bytes
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
package day2
import day1.*
import kotlinx.atomicfu.*
class FAABasedQueueSimplified<E> : Queue<E> {
private val infiniteArray = atomicArrayOfNulls<Any?>(1024) // conceptually infinite array
private val enqIdx = atomic(0)
private val deqIdx = atomic(0)
override fun enqueue(element: E) {
while (true) {
val i = enqIdx.getAndIncrement()
if (infiniteArray[i].compareAndSet(null, element)) {
return
}
}
}
@Suppress("UNCHECKED_CAST")
override fun dequeue(): E? {
// Is this queue empty?
while (true) {
if (deqIdx.value >= enqIdx.value) {
return null
}
val i = deqIdx.getAndIncrement()
if (infiniteArray[i].compareAndSet(null, POISONED)) {
continue
}
return infiniteArray[i].value as E
}
}
}
// TODO: poison cells with this value.
private val POISONED = Any()