Skip to content

Remove ThreadLocal from ThreadLocalMap when finishing UndispatchedCor… #3593

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

Merged
merged 3 commits into from
Jan 24, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 26 additions & 6 deletions kotlinx-coroutines-core/jvm/src/CoroutineContext.kt
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,21 @@ internal actual class UndispatchedCoroutine<in T>actual constructor (
* // and it also calls saveThreadContext and clearThreadContext
* }
*/
private var threadStateToRecover = ThreadLocal<Pair<CoroutineContext, Any?>>()
private val threadStateToRecover = ThreadLocal<Pair<CoroutineContext, Any?>>()

/*
* Indicates that a coroutine has a thread local elements associated with it
* and that 'threadStateToRecover'.
* Better than nullable thread-local for easier debugging.
*
* It is used as a performance optimization to avoid 'threadStateToRecover' and
* is prone to false-positives as it is never reset: otherwise
* it may lead to logical data races between suspensions point where
* coroutine is yet being suspended in one thread while already being resumed
* in another.
*/
@Volatile
private var threadLocalIsSet = false

init {
/*
Expand Down Expand Up @@ -213,19 +227,25 @@ internal actual class UndispatchedCoroutine<in T>actual constructor (
}

fun saveThreadContext(context: CoroutineContext, oldValue: Any?) {
threadLocalIsSet = true // Specify that thread-local is touched at all
threadStateToRecover.set(context to oldValue)
}

fun clearThreadContext(): Boolean {
if (threadStateToRecover.get() == null) return false
threadStateToRecover.set(null)
if (threadLocalIsSet && threadStateToRecover.get() == null) {
threadStateToRecover.remove()
return false
}
threadStateToRecover.remove()
return true
}

override fun afterResume(state: Any?) {
threadStateToRecover.get()?.let { (ctx, value) ->
restoreThreadContext(ctx, value)
threadStateToRecover.set(null)
if (threadLocalIsSet) {
threadStateToRecover.get()?.let { (ctx, value) ->
restoreThreadContext(ctx, value)
}
threadStateToRecover.remove()
}
// resume undispatched -- update context but stay on the same dispatcher
val result = recoverResult(state, uCont)
Expand Down