Skip to content

Commit ab03703

Browse files
committed
add optimistic tree and test for it
1 parent 4a8d99d commit ab03703

File tree

2 files changed

+20
-13
lines changed

2 files changed

+20
-13
lines changed

task4/src/main/kotlin/OptimisticTree.kt

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
package org.example
22

3-
import kotlinx.coroutines.sync.Mutex
4-
53
class OptimisticTree<K : Comparable<K>, V>: Tree<K, V>() {
64
private var root: TreeNode<K, V>? = null
7-
private val treeLock = Mutex()
85

96
private suspend fun searchAux(key: K): Pair<TreeNode<K, V>?, TreeNode<K, V>?> {
107
while (true) {
@@ -28,15 +25,15 @@ class OptimisticTree<K : Comparable<K>, V>: Tree<K, V>() {
2825

2926
var validationParent: TreeNode<K, V>? = root
3027
while (parent != validationParent) {
31-
val key = checkNotNull(validationParent?.key)
32-
validationParent = if (key < parent.key) validationParent?.right else validationParent?.left
33-
// if (validationParent == null) {
34-
// // again
35-
// validationParent = root
36-
// }
28+
val validationParentKey = checkNotNull(validationParent?.key)
29+
validationParent = if (validationParentKey < parent.key) validationParent?.right else validationParent?.left
30+
if (validationParent == null) {
31+
// again
32+
break
33+
}
3734
}
3835

39-
if (current == validationParent.left || current == validationParent.right) {
36+
if (current == validationParent?.left || current == validationParent?.right) {
4037
return current to parent
4138
} else {
4239
// retry
@@ -90,7 +87,7 @@ class OptimisticTree<K : Comparable<K>, V>: Tree<K, V>() {
9087
private suspend fun deleteRec(node: TreeNode<K, V>?, parent: TreeNode<K, V>?): TreeNode<K, V>? {
9188
when {
9289
node == null -> {
93-
parent?.unlock() ?: treeLock.unlock()
90+
parent?.unlock()
9491
return parent
9592
}
9693

@@ -108,7 +105,7 @@ class OptimisticTree<K : Comparable<K>, V>: Tree<K, V>() {
108105
}
109106
}
110107
node.unlock()
111-
parent?.unlock() ?: treeLock.unlock()
108+
parent?.unlock()
112109
}
113110

114111
else -> {
@@ -136,7 +133,7 @@ class OptimisticTree<K : Comparable<K>, V>: Tree<K, V>() {
136133

137134
right.unlock()
138135
node.unlock()
139-
parent?.unlock() ?: treeLock.unlock()
136+
parent?.unlock()
140137
}
141138
}
142139
return parent
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import org.example.OptimisticTree
2+
import org.junit.jupiter.api.BeforeEach
3+
4+
class OptimisticTreeTest : TreeTest() {
5+
6+
@BeforeEach
7+
override fun setUp() {
8+
tree = OptimisticTree()
9+
}
10+
}

0 commit comments

Comments
 (0)