-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Properly cleanup completion in SafeCollector to avoid unintended memo… (
#3199) * Properly cleanup completion in SafeCollector to avoid unintended memory leak that regular coroutines (e.g. unsafe flow) are not prone to Also, FieldWalker is improved to avoid "illegal reflective access" Fixes #3197 Co-authored-by: Roman Elizarov <[email protected]>
- Loading branch information
Showing
3 changed files
with
88 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 48 additions & 0 deletions
48
kotlinx-coroutines-core/jvm/test/flow/SafeCollectorMemoryLeakTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
/* | ||
* Copyright 2016-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package kotlinx.coroutines.flow | ||
|
||
import kotlinx.coroutines.* | ||
import org.junit.* | ||
|
||
class SafeCollectorMemoryLeakTest : TestBase() { | ||
// custom List.forEach impl to avoid using iterator (FieldWalker cannot scan it) | ||
private inline fun <T> List<T>.listForEach(action: (T) -> Unit) { | ||
for (i in indices) action(get(i)) | ||
} | ||
|
||
@Test | ||
fun testCompletionIsProperlyCleanedUp() = runBlocking { | ||
val job = flow { | ||
emit(listOf(239)) | ||
expect(2) | ||
hang {} | ||
}.transform { l -> l.listForEach { _ -> emit(42) } } | ||
.onEach { expect(1) } | ||
.launchIn(this) | ||
yield() | ||
expect(3) | ||
FieldWalker.assertReachableCount(0, job) { it == 239 } | ||
job.cancelAndJoin() | ||
finish(4) | ||
} | ||
|
||
@Test | ||
fun testCompletionIsNotCleanedUp() = runBlocking { | ||
val job = flow { | ||
emit(listOf(239)) | ||
hang {} | ||
}.transform { l -> l.listForEach { _ -> emit(42) } } | ||
.onEach { | ||
expect(1) | ||
hang { finish(3) } | ||
} | ||
.launchIn(this) | ||
yield() | ||
expect(2) | ||
FieldWalker.assertReachableCount(1, job) { it == 239 } | ||
job.cancelAndJoin() | ||
} | ||
} |