aboutsummaryrefslogtreecommitdiffstats
path: root/kotlinx-coroutines-core/jvm/test/JobChildStressTest.kt
blob: 107cc52cb5b4b2161cfe5c7f23e1581575b7596b (plain)
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
/*
 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.coroutines

import org.junit.*
import org.junit.Test
import java.util.concurrent.*
import kotlin.test.*

class JobChildStressTest : TestBase() {
    private val N_ITERATIONS = 10_000 * stressTestMultiplier
    private val pool = newFixedThreadPoolContext(3, "JobChildStressTest")

    @After
    fun tearDown() {
        pool.close()
    }

    /**
     * Perform concurrent launch of a child job & cancellation of the explicit parent job
     */
    @Test
    @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
    fun testChild() = runTest {
        val barrier = CyclicBarrier(3)
        repeat(N_ITERATIONS) {
            var wasLaunched = false
            var unhandledException: Throwable? = null
            val handler = CoroutineExceptionHandler { _, ex ->
                unhandledException = ex
            }
            val scope = CoroutineScope(pool + handler)
            val parent = CompletableDeferred<Unit>()
            // concurrent child launcher
            val launcher = scope.launch {
                barrier.await()
                // A: launch child for a parent job
                launch(parent) {
                    wasLaunched = true
                    throw TestException()
                }
            }
            // concurrent cancel
            val canceller = scope.launch {
                barrier.await()
                // B: cancel parent job of a child
                parent.cancel()
            }
            barrier.await()
            joinAll(launcher, canceller, parent)
            assertNull(unhandledException)
            if (wasLaunched) {
                val exception = parent.getCompletionExceptionOrNull()
                assertTrue(exception is TestException, "exception=$exception")
            }
        }
    }
}