public class ThreadContextElementKt
Modifier and Type | Method and Description |
---|---|
static <T> ThreadContextElement<T> |
asContextElement(java.lang.ThreadLocal<T> $receiver,
T value)
Wraps ThreadLocal into
interface ThreadContextElement . The resulting interface ThreadContextElement
maintains the given value of the given ThreadLocal for coroutine regardless of the actual thread its is resumed on.
By default ThreadLocal.get is used as a value for the thread-local variable, but it can be overridden with value parameter. |
public static <T> ThreadContextElement<T> asContextElement(java.lang.ThreadLocal<T> $receiver, T value)
Wraps ThreadLocal into interface ThreadContextElement
. The resulting interface ThreadContextElement
maintains the given value of the given ThreadLocal for coroutine regardless of the actual thread its is resumed on.
By default ThreadLocal.get is used as a value for the thread-local variable, but it can be overridden with value parameter.
Example usage looks like this:
val myThreadLocal = ThreadLocal()
...
println(myThreadLocal.get()) // Prints "null"
launch(Dispatchers.Default + myThreadLocal.asContextElement(value = "foo")) {
println(myThreadLocal.get()) // Prints "foo"
withContext(UI) {
println(myThreadLocal.get()) // Prints "foo", but it's on UI thread
}
}
println(myThreadLocal.get()) // Prints "null"
Note that the context element does not track modifications of the thread-local variable, for example:
myThreadLocal.set("main")
withContext(UI) {
println(myThreadLocal.get()) // Prints "main"
myThreadLocal.set("UI")
}
println(myThreadLocal.get()) // Prints "main", not "UI"
Use withContext
to update the corresponding thread-local variable to a different value, for example:
withContext(myThreadLocal.asContextElement("foo")) {
println(myThreadLocal.get()) // Prints "foo"
}