ensurePresent

inline suspend fun ThreadLocal<*>.ensurePresent()(source)

Checks whether current thread local is present in the coroutine context and throws IllegalStateException if it is not. It is a good practice to validate that thread local is present in the context, especially in large code-bases, to avoid stale thread-local values and to have a strict invariants.

E.g. one may use the following method to enforce proper use of the thread locals with coroutines:

public suspend inline fun <T> ThreadLocal<T>.getSafely(): T {
ensurePresent()
return get()
}

// Usage
withContext(...) {
val value = threadLocal.getSafely() // Fail-fast in case of improper context
}