• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package kotlinx.coroutines
2 
3 import kotlinx.coroutines.testing.*
4 import org.junit.*
5 
6 class CancelledAwaitStressTest : TestBase() {
7     private val n = 1000 * stressTestMultiplier
8 
9     /**
10      * Tests that memory does not leak from cancelled [Deferred.await]
11      */
12     @Test
<lambda>null13     fun testCancelledAwait() = runTest {
14         val d = async {
15             delay(Long.MAX_VALUE)
16         }
17         repeat(n) {
18             val waiter = launch(start = CoroutineStart.UNDISPATCHED) {
19                 val a = ByteArray(10000000) // allocate 10M of memory here
20                 d.await()
21                 keepMe(a) // make sure it is kept in state machine
22             }
23             waiter.cancel() // cancel await
24             yield() // complete the waiter job, release its memory
25         }
26         d.cancel() // done test
27     }
28 
29     /**
30      * Tests that memory does not leak from cancelled [Job.join]
31      */
32     @Test
<lambda>null33     fun testCancelledJoin() = runTest {
34         val j = launch {
35             delay(Long.MAX_VALUE)
36         }
37         repeat(n) {
38             val joiner = launch(start = CoroutineStart.UNDISPATCHED) {
39                 val a = ByteArray(10000000) // allocate 10M of memory here
40                 j.join()
41                 keepMe(a) // make sure it is kept in state machine
42             }
43             joiner.cancel() // cancel join
44             yield() // complete the joiner job, release its memory
45         }
46         j.cancel() // done test
47     }
48 
keepMenull49     private fun keepMe(a: ByteArray) {
50         // does nothing, makes sure the variable is kept in state-machine
51     }
52 }
53