Skip to content

Fix forever lock of main thread in runBlocking #2374

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

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
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
17 changes: 14 additions & 3 deletions kotlinx-coroutines-core/jvm/src/Builders.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

package kotlinx.coroutines

import java.util.concurrent.locks.*
import kotlin.contracts.*
import kotlin.coroutines.*

Expand Down Expand Up @@ -69,22 +68,34 @@ private class BlockingCoroutine<T>(
override fun afterCompletion(state: Any?) {
// wake up blocked thread
if (Thread.currentThread() != blockedThread)
LockSupport.unpark(blockedThread)
unpark(blockedThread)
}

@Suppress("UNCHECKED_CAST")
fun joinBlocking(): T {
registerTimeLoopThread()
try {
eventLoop?.incrementUseCount()
val isMainThread = Thread.currentThread().id == 1L
try {
while (true) {
@Suppress("DEPRECATION")
if (Thread.interrupted()) throw InterruptedException().also { cancelCoroutine(it) }
val parkNanos = eventLoop?.processNextEvent() ?: Long.MAX_VALUE
// note: process next even may loose unpark flag, so check if completed before parking
if (isCompleted) break
parkNanos(this, parkNanos)
if (parkNanos <= 0 || parkNanos >= Long.MAX_VALUE) {
0L
} else {
if (parkNanos > 10_000_000L && isMainThread) {
// Restrict long park MainThread. No more than 10ms. delay 1ms
1_000_000L
} else {
parkNanos
}
}.let {
parkNanos(this, it)
}
}
} finally { // paranoia
eventLoop?.decrementUseCount()
Expand Down
7 changes: 5 additions & 2 deletions kotlinx-coroutines-core/jvm/src/TimeSource.kt
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,13 @@ internal inline fun unregisterTimeLoopThread() {

@InlineOnly
internal inline fun parkNanos(blocker: Any, nanos: Long) {
timeSource?.parkNanos(blocker, nanos) ?: LockSupport.parkNanos(blocker, nanos)
if (0L <= nanos && nanos < Long.MAX_VALUE) {
timeSource?.parkNanos(blocker, nanos) ?: LockSupport.parkNanos(blocker, nanos)
}
}

@InlineOnly
internal inline fun unpark(thread: Thread) {
timeSource?.unpark(thread) ?: LockSupport.unpark(thread)
timeSource?.unpark(thread)
LockSupport.unpark(thread)
}