How to use code that relies on ThreadLocal with Kotlin coroutines

前端 未结 1 1677
一整个雨季
一整个雨季 2020-12-14 01:46

Some JVM frameworks use ThreadLocal to store the call context of a application, like the SLF4j MDC, transaction managers, security managers, and others.

相关标签:
1条回答
  • 2020-12-14 02:01

    Coroutine's analog to ThreadLocal is CoroutineContext.

    To interoperate with ThreadLocal-using libraries you need to implement a custom ContinuationInterceptor that supports framework-specific thread-locals.

    Here is an example. Let us assume that we use some framework that relies on a specific ThreadLocal to store some application-specific data (MyData in this example):

    val myThreadLocal = ThreadLocal<MyData>()
    

    To use it with coroutines, you'll need to implement a context that keeps the current value of MyData and puts it into the corresponding ThreadLocal every time the coroutine is resumed on a thread. The code should look like this:

    class MyContext(
        private var myData: MyData,
        private val dispatcher: ContinuationInterceptor
    ) : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
        override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> =
            dispatcher.interceptContinuation(Wrapper(continuation))
    
        inner class Wrapper<T>(private val continuation: Continuation<T>): Continuation<T> {
            private inline fun wrap(block: () -> Unit) {
                try {
                    myThreadLocal.set(myData)
                    block()
                } finally {
                    myData = myThreadLocal.get()
                }
            }
    
            override val context: CoroutineContext get() = continuation.context
            override fun resume(value: T) = wrap { continuation.resume(value) }
            override fun resumeWithException(exception: Throwable) = wrap { continuation.resumeWithException(exception) }
        }
    }
    

    To use it in your coroutines, you wrap the dispatcher that you want to use with MyContext and give it the initial value of your data. This value will be put into the thread-local on the thread where the coroutine is resumed.

    launch(MyContext(MyData(), CommonPool)) {
        // do something...
    }
    

    The implementation above would also track any changes to the thread-local that was done and store it in this context, so this way multiple invocation can share "thread-local" data via context.

    UPDATE: Starting with kotlinx.corutines version 0.25.0 there is direct support for representing Java ThreadLocal instances as coroutine context elements. See this documentation for details. There is also out-of-the-box support for SLF4J MDC via kotlinx-coroutines-slf4j integration module.

    0 讨论(0)
提交回复
热议问题