Skip to content

Introduce a rendezvous on CancellableContinuationImpl.parentHandle to… #3380

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 1 commit into from
Aug 2, 2022
Merged
Changes from all 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
29 changes: 25 additions & 4 deletions kotlinx-coroutines-core/common/src/CancellableContinuationImpl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,28 @@ internal open class CancellableContinuationImpl<in T>(
*/
private val _state = atomic<Any?>(Active)

private var parentHandle: DisposableHandle? = null
/*
* This field has a concurrent rendezvous in the following scenario:
*
* - installParentHandle publishes this instance on T1
*
* T1 writes:
* * handle = installed; right after the installation
* * Shortly after: if (isComplete) handle = NonDisposableHandle
*
* Any other T writes if the parent job is cancelled in detachChild:
* * handle = NonDisposableHandle
*
* We want to preserve a strict invariant on parentHandle transition, allowing only three of them:
* null -> anyHandle
* anyHandle -> NonDisposableHandle
* null -> NonDisposableHandle
*
* With a guarantee that after disposal the only state handle may end up in is NonDisposableHandle
*/
private val _parentHandle = atomic<DisposableHandle?>(null)
private val parentHandle: DisposableHandle?
get() = _parentHandle.value

internal val state: Any? get() = _state.value

Expand Down Expand Up @@ -101,7 +122,7 @@ internal open class CancellableContinuationImpl<in T>(
if (isCompleted) {
// Can be invoked concurrently in 'parentCancelled', no problems here
handle.dispose()
parentHandle = NonDisposableHandle
_parentHandle.value = NonDisposableHandle
}
}

Expand Down Expand Up @@ -307,7 +328,7 @@ internal open class CancellableContinuationImpl<in T>(
onCancelling = true,
handler = ChildContinuation(this).asHandler
)
parentHandle = handle
_parentHandle.compareAndSet(null, handle)
return handle
}

Expand Down Expand Up @@ -492,7 +513,7 @@ internal open class CancellableContinuationImpl<in T>(
internal fun detachChild() {
val handle = parentHandle ?: return
handle.dispose()
parentHandle = NonDisposableHandle
_parentHandle.value = NonDisposableHandle
}

// Note: Always returns RESUME_TOKEN | null
Expand Down