Skip to content

Commit 0d35c85

Browse files
committed
Fixed quite a race in runBlocking that resulted in AssertionError
1 parent fdd6db5 commit 0d35c85

File tree

3 files changed

+8
-5
lines changed

3 files changed

+8
-5
lines changed

CHANGES.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
having to use `try/catch` or other exception handlers.
88
* Fixed a race in `ArrayBroadcastChannel` between `send` and `openChannel` invocations
99
(see #138).
10+
* Fixed quite a rare race in `runBlocking` that resulted in `AssertionError`.
11+
Unfortunately, cannot write a reliable stress-test to reproduce it.
1012
* Updated Reactor support to leverage Bismuth release train
1113
(contributed by @sdeleuze, see PR #141)
1214

core/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/Builders.kt

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -216,9 +216,6 @@ private class BlockingCoroutine<T>(
216216
}
217217

218218
override fun afterCompletion(state: Any?, mode: Int) {
219-
// signal termination to event loop (don't accept more tasks)
220-
if (privateEventLoop)
221-
(eventLoop as BlockingEventLoop).isCompleted = true
222219
// wake up blocked thread
223220
if (Thread.currentThread() != blockedThread)
224221
LockSupport.unpark(blockedThread)
@@ -235,7 +232,12 @@ private class BlockingCoroutine<T>(
235232
timeSource.parkNanos(this, parkNanos)
236233
}
237234
// process queued events (that could have been added after last processNextEvent and before cancel
238-
if (privateEventLoop) (eventLoop as BlockingEventLoop).shutdown()
235+
if (privateEventLoop) (eventLoop as BlockingEventLoop).apply {
236+
// We exit the "while" loop above when this coroutine's state "isCompleted",
237+
// Here we should signal that BlockingEventLoop should not accept any more tasks
238+
isCompleted = true
239+
shutdown()
240+
}
239241
timeSource.unregisterTimeLoopThread()
240242
// now return result
241243
val state = this.state

core/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/EventLoop.kt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,6 @@ internal abstract class ThreadEventLoop(
265265
// reschedule the rest of delayed tasks
266266
rescheduleAllDelayed()
267267
}
268-
269268
}
270269

271270
private class EventLoopImpl(thread: Thread) : ThreadEventLoop(thread) {

0 commit comments

Comments
 (0)