Skip to content
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

Provide safety mechanisms for working with thread-locals #1028

Closed
qwwdfsad opened this issue Mar 6, 2019 · 1 comment
Closed

Provide safety mechanisms for working with thread-locals #1028

qwwdfsad opened this issue Mar 6, 2019 · 1 comment
Assignees

Comments

@qwwdfsad
Copy link
Collaborator

qwwdfsad commented Mar 6, 2019

Currently, kotlinx.coroutines provides primitives to work with thread locals.

The problem is that they are not quite safe and it is easy to accidentally forget them (#1016).
Moreover, sometimes it is necessary to know whether thread local is present in the context in order to do some action (e.g. probabilistic request tracing using thread locals, the case from Circlet).

In all cases, it is impossible to check whether thread local element is actually present in the context, and checking thread local itself is not an option, because it can have a stale or default value.

We can provide following extensions (similar to coroutineContext) to cover that cases and promote their usages in the documentation:

suspend fun TheadLocal<*>.ensurePresent(): Unit
suspend fun TheadLocal<*>.isPresent(): Boolean
suspend inline fun <T> ThreadLocal<T>.ifPresent(block: suspend (T) -> Unit) // Or R?
@qwwdfsad qwwdfsad self-assigned this Mar 6, 2019
@glebleonov
Copy link

suspend inline fun <T> ThreadLocal<T>.ifPresent(block: suspend (T) -> R): R? would be better since one can use it like the following:

suspend fun <T> runWithMyThreadLocal(f: () -> T): T {
    return myThreadLocal.ifPresent {
        it.doSomethingWith(f())    
    } ?: f()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants