Skip to content

Properly use UndispatchedCoroutine context for context-specific elements #3413

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

Merged
merged 1 commit into from
Sep 27, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion kotlinx-coroutines-core/common/src/Builders.common.kt
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public suspend fun <T> withContext(
if (newContext[ContinuationInterceptor] == oldContext[ContinuationInterceptor]) {
val coroutine = UndispatchedCoroutine(newContext, uCont)
// There are changes in the context, so this thread needs to be updated
withCoroutineContext(newContext, null) {
withCoroutineContext(coroutine.context, null) {
return@sc coroutine.startUndispatchedOrReturn(coroutine, block)
}
}
Expand Down
35 changes: 35 additions & 0 deletions kotlinx-coroutines-core/jvm/test/ThreadContextElementTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,41 @@ class ThreadContextElementTest : TestBase() {
}
}
}

class JobCaptor(val capturees: ArrayList<Job> = ArrayList()) : ThreadContextElement<Unit> {

companion object Key : CoroutineContext.Key<MyElement>

override val key: CoroutineContext.Key<*> get() = Key

override fun updateThreadContext(context: CoroutineContext) {
capturees.add(context.job)
}

override fun restoreThreadContext(context: CoroutineContext, oldState: Unit) {
}
}

@Test
fun testWithContextJobAccess() = runTest {
val captor = JobCaptor()
val manuallyCaptured = ArrayList<Job>()
runBlocking(captor) {
manuallyCaptured += coroutineContext.job
withContext(CoroutineName("undispatched")) {
manuallyCaptured += coroutineContext.job
withContext(Dispatchers.IO) {
manuallyCaptured += coroutineContext.job
}
// Context restored, captured again
manuallyCaptured += coroutineContext.job
}
// Context restored, captured again
manuallyCaptured += coroutineContext.job
}

assertEquals(manuallyCaptured, captor.capturees)
}
}

class MyData
Expand Down