Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix leak of subscription reference in closed ArrayBroadcastChannel #1885

Merged
merged 1 commit into from Mar 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -218,13 +218,15 @@ internal class ArrayBroadcastChannel<E>(
override val isBufferAlwaysFull: Boolean get() = error("Should not be used")
override val isBufferFull: Boolean get() = error("Should not be used")

override fun onCancelIdempotent(wasClosed: Boolean) {
override fun close(cause: Throwable?): Boolean {
qwwdfsad marked this conversation as resolved.
Show resolved Hide resolved
val wasClosed = super.close(cause)
if (wasClosed) {
broadcastChannel.updateHead(removeSub = this)
subLock.withLock {
subHead = broadcastChannel.tail
}
}
return wasClosed
}

// returns true if subHead was updated and broadcast channel's head must be checked
Expand Down
@@ -0,0 +1,34 @@
package kotlinx.coroutines.channels

import kotlinx.coroutines.*
import org.junit.Test
import kotlin.test.*

class BroadcastChannelLeakTest : TestBase() {
@Test
fun testArrayBroadcastChannelSubscriptionLeak() {
checkLeak { ArrayBroadcastChannel(1) }
}

@Test
fun testConflatedBroadcastChannelSubscriptionLeak() {
checkLeak { ConflatedBroadcastChannel() }
}

enum class TestKind { BROADCAST_CLOSE, SUB_CANCEL, BOTH }

private fun checkLeak(factory: () -> BroadcastChannel<String>) = runTest {
for (kind in TestKind.values()) {
val broadcast = factory()
val sub = broadcast.openSubscription()
broadcast.send("OK")
assertEquals("OK", sub.receive())
// now close broadcast
if (kind != TestKind.SUB_CANCEL) broadcast.close()
// and then cancel subscription
if (kind != TestKind.BROADCAST_CLOSE) sub.cancel()
// subscription should not be reachable from the channel anymore
FieldWalker.assertReachableCount(0, broadcast) { it === sub }
}
}
}