-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathTreiberStack.kt
More file actions
31 lines (26 loc) · 857 Bytes
/
Copy pathTreiberStack.kt
File metadata and controls
31 lines (26 loc) · 857 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
package day1
import java.util.concurrent.atomic.AtomicReference
class TreiberStack<E> : Stack<E> {
// Initially, the stack is empty.
private val top = AtomicReference<Node<E>?>(null)
override fun push(element: E) {
// TODO: Make me linearizable!
// TODO: Update `top` via Compare-and-Set,
// TODO: restarting the operation on CAS failure.
val curTop = top.get()
val newTop = Node(element, curTop)
top.set(newTop)
}
override fun pop(): E? {
// TODO: Make me linearizable!
// TODO: Update `top` via Compare-and-Set,
// TODO: restarting the operation on CAS failure.
val curTop = top.get() ?: return null
top.set(curTop.next)
return curTop.element
}
private class Node<E>(
val element: E,
val next: Node<E>?
)
}