Skip to content

Commit ad84795

Browse files
committed
Slightly faster update to finishing state on completion
1 parent f45ec8d commit ad84795

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

common/kotlinx-coroutines-core-common/src/JobSupport.kt

+6-4
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,12 @@ internal open class JobSupport constructor(active: Boolean) : Job, SelectClause0
800800
if (finishing.isCompleting) return COMPLETING_ALREADY_COMPLETING
801801
// mark as completing
802802
finishing.isCompleting = true
803+
// if we need to promote to finishing then atomically do it here.
804+
// We do it as early is possible while still holding the lock. This ensures that we fail asap
805+
// (if somebody else is faster) and we synchronize all the threads on this finishing lock asap.
806+
if (finishing !== state) {
807+
if (!_state.compareAndSet(state, finishing)) return COMPLETING_RETRY
808+
}
803809
// ## IMPORTANT INVARIANT: Only one thread (that had set isCompleting) can go past this point
804810
require(!finishing.isSealed) // cannot be sealed
805811
// mark as cancelling is the proposed update is to cancel
@@ -810,10 +816,6 @@ internal open class JobSupport constructor(active: Boolean) : Job, SelectClause0
810816
// If it just becomes failing --> must process failing notifications
811817
notifyRootCause = finishing.rootCause.takeIf { !wasFailing }
812818
}
813-
// if we need to promote to finishing then atomically do it here
814-
if (finishing !== state) {
815-
if (!_state.compareAndSet(state, finishing)) return COMPLETING_RETRY
816-
}
817819
// process failing notification here -- it cancels all the children _before_ we start to to wait them (sic!!!)
818820
notifyRootCause?.let { notifyFailing(list, it) }
819821
// now wait for children

0 commit comments

Comments
 (0)