From a15d20a59838fa1b9a7f63e10f31f475e633f62a Mon Sep 17 00:00:00 2001 From: Vsevolod Tolstopyatov Date: Fri, 13 Nov 2020 18:50:12 +0300 Subject: [PATCH] Conditionally create an instance of CancellationException in Channel.cancel() Avoid creating costly exception when the channel is cancelled to save a few cycles when it's not necessary. Cancellation is heavy-enough when the channel is open, so the single check won't worsen it. --- kotlinx-coroutines-core/common/src/channels/AbstractChannel.kt | 1 + kotlinx-coroutines-core/common/src/channels/ChannelCoroutine.kt | 1 + kotlinx-coroutines-core/common/src/flow/internal/Combine.kt | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/kotlinx-coroutines-core/common/src/channels/AbstractChannel.kt b/kotlinx-coroutines-core/common/src/channels/AbstractChannel.kt index 8edd2b310c..87bd43714d 100644 --- a/kotlinx-coroutines-core/common/src/channels/AbstractChannel.kt +++ b/kotlinx-coroutines-core/common/src/channels/AbstractChannel.kt @@ -635,6 +635,7 @@ internal abstract class AbstractChannel( cancelInternal(cause) final override fun cancel(cause: CancellationException?) { + if (isClosedForReceive) return // Do not create an exception if channel is already cancelled cancelInternal(cause ?: CancellationException("$classSimpleName was cancelled")) } diff --git a/kotlinx-coroutines-core/common/src/channels/ChannelCoroutine.kt b/kotlinx-coroutines-core/common/src/channels/ChannelCoroutine.kt index a75d466199..9ceb77ddc2 100644 --- a/kotlinx-coroutines-core/common/src/channels/ChannelCoroutine.kt +++ b/kotlinx-coroutines-core/common/src/channels/ChannelCoroutine.kt @@ -26,6 +26,7 @@ internal open class ChannelCoroutine( } final override fun cancel(cause: CancellationException?) { + if (isClosedForReceive) return // Do not create an exception if channel is already cancelled cancelInternal(cause ?: defaultCancellationException()) } diff --git a/kotlinx-coroutines-core/common/src/flow/internal/Combine.kt b/kotlinx-coroutines-core/common/src/flow/internal/Combine.kt index bbdebd08b9..d276e5100a 100644 --- a/kotlinx-coroutines-core/common/src/flow/internal/Combine.kt +++ b/kotlinx-coroutines-core/common/src/flow/internal/Combine.kt @@ -137,7 +137,7 @@ internal fun zipImpl(flow: Flow, flow2: Flow, transform: sus } catch (e: AbortFlowException) { e.checkOwnership(owner = this@unsafeFlow) } finally { - if (!second.isClosedForReceive) second.cancel() + second.cancel() } } }