-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathThreadSafeHeapTest.kt
96 lines (90 loc) · 2.95 KB
/
ThreadSafeHeapTest.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import kotlinx.coroutines.*
import kotlin.test.*
import java.util.*
class ThreadSafeHeapTest : TestBase() {
internal class Node(val value: Int) : ThreadSafeHeapNode, Comparable<Node> {
override var heap: ThreadSafeHeap<*>? = null
override var index = -1
override fun compareTo(other: Node): Int = value.compareTo(other.value)
override fun equals(other: Any?): Boolean = other is Node && other.value == value
override fun hashCode(): Int = value
override fun toString(): String = "$value"
}
@Test
fun testBasic() {
val h = ThreadSafeHeap<Node>()
assertNull(h.peek())
val n1 = Node(1)
h.addLast(n1)
assertEquals(n1, h.peek())
val n2 = Node(2)
h.addLast(n2)
assertEquals(n1, h.peek())
val n3 = Node(3)
h.addLast(n3)
assertEquals(n1, h.peek())
val n4 = Node(4)
h.addLast(n4)
assertEquals(n1, h.peek())
val n5 = Node(5)
h.addLast(n5)
assertEquals(n1, h.peek())
assertEquals(n1, h.removeFirstOrNull())
assertEquals(-1, n1.index)
assertEquals(n2, h.peek())
h.remove(n2)
assertEquals(n3, h.peek())
h.remove(n4)
assertEquals(n3, h.peek())
h.remove(n3)
assertEquals(n5, h.peek())
h.remove(n5)
assertNull(h.peek())
}
@Test
fun testRandomSort() {
val n = 1000 * stressTestMultiplier
val r = Random(1)
val h = ThreadSafeHeap<Node>()
val a = IntArray(n) { r.nextInt() }
repeat(n) { h.addLast(Node(a[it])) }
a.sort()
repeat(n) { assertEquals(Node(a[it]), h.removeFirstOrNull()) }
assertNull(h.peek())
}
@Test
fun testRandomRemove() {
val n = 1000 * stressTestMultiplier
check(n % 2 == 0) { "Must be even" }
val r = Random(1)
val h = ThreadSafeHeap<Node>()
val set = TreeSet<Node>()
repeat(n) {
val node = Node(r.nextInt())
h.addLast(node)
assertTrue(set.add(node))
}
while (!h.isEmpty) {
// pick random node to remove
val rndNode: Node
while (true) {
val tail = set.tailSet(Node(r.nextInt()))
if (!tail.isEmpty()) {
rndNode = tail.first()
break
}
}
assertTrue(set.remove(rndNode))
assertTrue(h.remove(rndNode))
// remove head and validate
val headNode = h.removeFirstOrNull()!! // must not be null!!!
assertSame(headNode, set.first(), "Expected ${set.first()}, but found $headNode, remaining size ${h.size}")
assertTrue(set.remove(headNode))
assertEquals(set.size, h.size)
}
}
}