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

package kotlinx.coroutines.selects

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlin.test.*

class SelectMemoryLeakStressTest : TestBase() {
    private val nRepeat = 1_000_000 * stressTestMultiplier

    @Test
    fun testLeakRegisterSend() = runTest {
        expect(1)
        val leak = Channel<String>()
        val data = Channel<Int>(1)
        repeat(nRepeat) { value ->
            data.send(value)
            val bigValue = bigValue() // new instance
            select {
                leak.onSend("LEAK") {
                    println("Capture big value into this lambda: $bigValue")
                    expectUnreached()
                }
                data.onReceive { received ->
                    assertEquals(value, received)
                    expect(value + 2)
                }
            }
        }
        finish(nRepeat + 2)
    }

    @Test
    fun testLeakRegisterReceive() = runTest {
        expect(1)
        val leak = Channel<String>()
        val data = Channel<Int>(1)
        repeat(nRepeat) { value ->
            val bigValue = bigValue() // new instance
            select<Unit> {
                leak.onReceive {
                    println("Capture big value into this lambda: $bigValue")
                    expectUnreached()
                }
                data.onSend(value) {
                    expect(value + 2)
                }
            }
            assertEquals(value, data.receive())
        }
        finish(nRepeat + 2)
    }

    // capture big value for fast OOM in case of a bug
    private fun bigValue(): ByteArray = ByteArray(4096)
}