martmists
11/27/2024, 12:07 AMmyThreadLocal.get()
simply reports as null even though it shouldn't be, as the sync call is nested far down inside coroutineContext(myThreadLocal.asContextElement(nonNullValue)) { /* get happens inside here */ }
My use-case is a custom JDBC driver wrapper providing SQL trace data to the current coroutine by modifying a MutableList.Dmitry Khalanskiy [JB]
11/27/2024, 9:49 AMit doesn't seem to update the ThreadLocal across dispatchersBut it does. https://pl.kotl.in/GzEXDglfe
I don't know where thiscoroutineContext(myThreadLocal.asContextElement(nonNullValue)) {
coroutineContext
function comes from, but it's not from kotlinx.coroutines
, as our coroutineContext
only accepts the lambda argument and nothing else.martmists
11/27/2024, 11:44 AMwithContext
, my bad.martmists
11/27/2024, 11:46 AMDmitry Khalanskiy [JB]
11/27/2024, 12:01 PMasContextElement
behaves, so it could be a good starting point. If the documentation is somehow incorrect/misleading, please let us know, and we'll fix it.martmists
11/27/2024, 12:06 PMDmitry Khalanskiy [JB]
11/27/2024, 12:13 PMnewSuspendedTransaction
does exactly. As a kotlinx.coroutines
maintainer, I'm suspicious of `coroutineContext + Dispatchers.IO`: usually, doing coroutineContext +
shouldn't be needed, each operation should preserve the surrounding context. Does newSuspendedTransaction(<http://Dispatchers.IO|Dispatchers.IO>)
also not work?martmists
11/27/2024, 12:20 PMmartmists
11/27/2024, 12:23 PM<http://Dispatchers.IO|Dispatchers.IO> + tls.asContextElement(tls.get())
does work however.Dmitry Khalanskiy [JB]
11/27/2024, 12:24 PMtls.asContextElement
. Otherwise, coroutineContext + <http://Dispatchers.IO|Dispatchers.IO>
should have worked.Dmitry Khalanskiy [JB]
11/27/2024, 12:27 PMmartmists
11/27/2024, 2:26 PMThen it looks like your original context doesn't containI'm not sure how that happens, throwing an exception clearly shows it inside the. Otherwise,tls.asContextElement
should have worked.coroutineContext + <http://Dispatchers.IO|Dispatchers.IO>
withContext(tls.asContextElement(...))
so it should be theremartmists
11/27/2024, 5:12 PMvar wrapper: suspend (content: suspend () -> Unit) -> Unit = { it() }
wrapper = {
// tls no longer in coroutineContext according to IntelliJ debugger
newSuspendedTransaction(Dispatchers.IO) {
it()
}
}
// ...
// tls in coroutineContext
async {
// tls in coroutineContext
wrapper {
// ...
It looks like the suspending function as property may have some weird handling.martmists
11/27/2024, 5:53 PMDmitry Khalanskiy [JB]
11/28/2024, 11:06 AMmartmists
11/28/2024, 12:02 PMDmitry Khalanskiy [JB]
11/29/2024, 7:38 AM