Skip to content

Commit

Permalink
Conditionally create an instance of CancellationException in Channel.…
Browse files Browse the repository at this point in the history
…cancel() (#2384)

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.
  • Loading branch information
qwwdfsad committed Nov 16, 2020
1 parent dede17e commit bc553ba
Show file tree
Hide file tree
Showing 3 changed files with 3 additions and 1 deletion.
Expand Up @@ -635,6 +635,7 @@ internal abstract class AbstractChannel<E>(
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"))
}

Expand Down
Expand Up @@ -26,6 +26,7 @@ internal open class ChannelCoroutine<E>(
}

final override fun cancel(cause: CancellationException?) {
if (isClosedForReceive) return // Do not create an exception if channel is already cancelled
cancelInternal(cause ?: defaultCancellationException())
}

Expand Down
Expand Up @@ -137,7 +137,7 @@ internal fun <T1, T2, R> zipImpl(flow: Flow<T1>, flow2: Flow<T2>, transform: sus
} catch (e: AbortFlowException) {
e.checkOwnership(owner = this@unsafeFlow)
} finally {
if (!second.isClosedForReceive) second.cancel()
second.cancel()
}
}
}

0 comments on commit bc553ba

Please sign in to comment.