blob: d8dad31c8a3470f4637ecb6a1311d71038a23638 [file] [log] [blame]
Vsevolod Tolstopyatov98b04d42018-03-27 20:46:00 +03001package kotlinx.coroutines.experimental.scheduling
2
3import kotlinx.coroutines.experimental.*
4import org.junit.After
5import org.junit.Test
6import java.util.concurrent.atomic.AtomicBoolean
7import kotlin.test.assertEquals
8import kotlin.test.assertNull
9
10class CoroutineSchedulerTest : TestBase() {
11
12 var dispatcher: ExperimentalCoroutineDispatcher? = null
13
14 @After
15 fun tearDown() {
16 schedulerTimeSource = NanoTimeSource
17 dispatcher?.close()
18 }
19
20 @Test
21 fun testSingleThread() = runBlocking {
22 dispatcher = ExperimentalCoroutineDispatcher(1)
23 expect(1)
24 withContext(dispatcher!!) {
25 require(Thread.currentThread().name.contains("CoroutinesScheduler-worker"))
26 expect(2)
27 val job = async(coroutineContext) {
28 expect(3)
29 delay(10)
30 expect(4)
31 }
32
33 job.await()
34 expect(5)
35 }
36
37 finish(6)
38 }
39
40 @Test
41 fun testStealing() = runBlocking {
42 dispatcher = ExperimentalCoroutineDispatcher(2)
43 val flag = AtomicBoolean(false)
44 val job = async(context = dispatcher!!) {
45 expect(1)
46 val innerJob = async {
47 expect(2)
48 flag.set(true)
49 }
50
51 while (!flag.get()) {
52 Thread.yield() // Block current thread, submitted inner job will be stolen
53 }
54
55 innerJob.await()
56 expect(3)
57 }
58
59 job.await()
60 finish(4)
61 }
62
63 @Test
64 fun testNoStealing() = runBlocking {
65 dispatcher = ExperimentalCoroutineDispatcher()
66 schedulerTimeSource = TestTimeSource(0L)
67 withContext(dispatcher!!) {
68 val thread = Thread.currentThread()
69 val job = async(dispatcher!!) {
70 assertEquals(thread, Thread.currentThread())
71 val innerJob = async(dispatcher!!) {
72 assertEquals(thread, Thread.currentThread())
73 }
74 innerJob.await()
75 }
76
77 job.await()
78 assertEquals(thread, Thread.currentThread())
79 }
80 }
81
82 @Test
83 fun testDelay() = runBlocking {
84 dispatcher = ExperimentalCoroutineDispatcher(2)
85 withContext(dispatcher!!) {
86 expect(1)
87 delay(10)
88 expect(2)
89 }
90
91 finish(3)
92 }
93
94 @Test
95 fun testWithTimeout() = runBlocking {
96 dispatcher = ExperimentalCoroutineDispatcher()
97 withContext(dispatcher!!) {
98 expect(1)
99 val result = withTimeoutOrNull(1000) {
100 expect(2)
101 yield() // yield only now
102 "OK"
103 }
104 assertEquals("OK", result)
105
106 val nullResult = withTimeoutOrNull(1000) {
107 expect(3)
108 while (true) {
109 yield()
110 }
111
112 "OK"
113 }
114
115 assertNull(nullResult)
116 finish(4)
117 }
118 }
119}