Skip to content

ThreadLocal element not updated correctly when using UnconfinedTestDispatcher #4326

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

Closed
chuckjaz opened this issue Jan 10, 2025 · 1 comment
Closed
Labels

Comments

@chuckjaz
Copy link

When using an UnconfinedTestDispatcher, the context element for a thread local is not restored when the coroutine is suspended.

Reproduction

playground

import kotlin.coroutines.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.test.*

val MyThreadLocal = ThreadLocal<String>().apply { set("initial") }

@OptIn(ExperimentalCoroutinesApi::class)
fun main() = runTest(UnconfinedTestDispatcher()) {
    val toResume = CompletableDeferred<Continuation<Unit>>()
    launch {
    	println("Initial value: ${MyThreadLocal.get()}")
    	withContext(MyThreadLocal.asContextElement(value = "inContext")) {
        	println("in withContext: ${MyThreadLocal.get()}")
        	suspendCoroutine { co ->
            	toResume.complete(co)
        	}
   		}
        println("after withContext: ${MyThreadLocal.get()}")
    }
    toResume.await().resume(Unit)
}

Expected: "after withContext: initial"

Received: "after withContext: inContext"

NOTE: Removing (UnconfinedTestDispatcher()) from the test case above produces the expected result.

This seems related to #2930 and #4121 as the repro steps are similar.

@chuckjaz chuckjaz added the bug label Jan 10, 2025
@dkhalanskyjb
Copy link
Collaborator

Duplicate of #4121; this is not a bug but documented behavior. Your main coroutine attempts to access a value access to which it hasn't declared. You can fix the issue by replacing

fun main() = runTest(UnconfinedTestDispatcher()) {

with

fun main() = runTest(UnconfinedTestDispatcher() + MyThreadLocal.asContextElement()) {

If you feel this is inadequate, please join #4121 and explain your use case!

@dkhalanskyjb dkhalanskyjb closed this as not planned Won't fix, can't repro, duplicate, stale Jan 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants