Skip to content

Commit 0f0385a

Browse files
committed
Do not touch thread-locals if they were never set in UndispatchedCoroutine
1 parent 4d72c30 commit 0f0385a

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

kotlinx-coroutines-core/jvm/src/CoroutineContext.kt

+10-5
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,9 @@ internal actual class UndispatchedCoroutine<in T>actual constructor (
179179
* // and it also calls saveThreadContext and clearThreadContext
180180
* }
181181
*/
182-
private var threadStateToRecover = ThreadLocal<Pair<CoroutineContext, Any?>>()
182+
private val threadStateToRecover = ThreadLocal<Pair<CoroutineContext, Any?>>()
183+
@Volatile
184+
private var threadLocalIsSet = false // Better than nullable thread-local for easier debugging
183185

184186
init {
185187
/*
@@ -213,11 +215,12 @@ internal actual class UndispatchedCoroutine<in T>actual constructor (
213215
}
214216

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

219222
fun clearThreadContext(): Boolean {
220-
if (threadStateToRecover.get() == null) {
223+
if (threadLocalIsSet && threadStateToRecover.get() == null) {
221224
threadStateToRecover.remove()
222225
return false
223226
}
@@ -226,10 +229,12 @@ internal actual class UndispatchedCoroutine<in T>actual constructor (
226229
}
227230

228231
override fun afterResume(state: Any?) {
229-
threadStateToRecover.get()?.let { (ctx, value) ->
230-
restoreThreadContext(ctx, value)
232+
if (threadLocalIsSet) {
233+
threadStateToRecover.get()?.let { (ctx, value) ->
234+
restoreThreadContext(ctx, value)
235+
}
236+
threadStateToRecover.remove()
231237
}
232-
threadStateToRecover.remove()
233238
// resume undispatched -- update context but stay on the same dispatcher
234239
val result = recoverResult(state, uCont)
235240
withContinuationContext(uCont, null) {

0 commit comments

Comments
 (0)