1 /* 2 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 5 package kotlinx.coroutines 6 7 import org.junit.* 8 9 class CancelledAwaitStressTest : TestBase() { 10 private val n = 1000 * stressTestMultiplier 11 12 /** 13 * Tests that memory does not leak from cancelled [Deferred.await] 14 */ 15 @Test <lambda>null16 fun testCancelledAwait() = runTest { 17 val d = async { 18 delay(Long.MAX_VALUE) 19 } 20 repeat(n) { 21 val waiter = launch(start = CoroutineStart.UNDISPATCHED) { 22 val a = ByteArray(10000000) // allocate 10M of memory here 23 d.await() 24 keepMe(a) // make sure it is kept in state machine 25 } 26 waiter.cancel() // cancel await 27 yield() // complete the waiter job, release its memory 28 } 29 d.cancel() // done test 30 } 31 32 /** 33 * Tests that memory does not leak from cancelled [Job.join] 34 */ 35 @Test <lambda>null36 fun testCancelledJoin() = runTest { 37 val j = launch { 38 delay(Long.MAX_VALUE) 39 } 40 repeat(n) { 41 val joiner = launch(start = CoroutineStart.UNDISPATCHED) { 42 val a = ByteArray(10000000) // allocate 10M of memory here 43 j.join() 44 keepMe(a) // make sure it is kept in state machine 45 } 46 joiner.cancel() // cancel join 47 yield() // complete the joiner job, release its memory 48 } 49 j.cancel() // done test 50 } 51 keepMenull52 private fun keepMe(a: ByteArray) { 53 // does nothing, makes sure the variable is kept in state-machine 54 } 55 }