Skip to content

Commit

Permalink
Handle unexpected exceptions in the dispatcher when throwing runnable…
Browse files Browse the repository at this point in the history
… is passed as an argument
  • Loading branch information
qwwdfsad committed Sep 20, 2021
1 parent f0a265a commit 00122c5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ internal class LimitedDispatcher(
while (true) {
val task = queue.removeFirstOrNull()
if (task != null) {
task.run()
try {
task.run()
} catch (e: Throwable) {
handleCoroutineException(EmptyCoroutineContext, e)
}
// 16 is our out-of-thin-air constant to emulate fairness. Used in JS dispatchers as well
if (++fairnessCounter >= 16 && dispatcher.isDispatchNeeded(EmptyCoroutineContext)) {
// Do "yield" to let other views to execute their runnable as well
Expand Down Expand Up @@ -62,8 +66,7 @@ internal class LimitedDispatcher(
}

/*
* Protect against race when the worker is finished
* right after our check
* Protect against race when the worker is finished right after our check.
*/
@Suppress("CAST_NEVER_SUCCEEDS")
synchronized(this as SynchronizedObject) {
Expand Down
24 changes: 23 additions & 1 deletion kotlinx-coroutines-core/jvm/test/LimitedParallelismTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

package kotlinx.coroutines

import org.junit.*
import org.junit.Test
import java.util.concurrent.*
import kotlin.coroutines.*
import kotlin.test.*

class LimitedParallelismTest : TestBase() {

Expand All @@ -30,4 +33,23 @@ class LimitedParallelismTest : TestBase() {
joinAll(j1, j2)
executor.close()
}

@Test
fun testUnhandledException() = runTest {
var caughtException: Throwable? = null
val executor = Executors.newFixedThreadPool(
1
) {
Thread(it).also {
it.uncaughtExceptionHandler = Thread.UncaughtExceptionHandler { _, e -> caughtException = e }
}
}.asCoroutineDispatcher()
val view = executor.limitedParallelism(1)
view.dispatch(EmptyCoroutineContext, Runnable { throw TestException() })
withContext(view) {
// Verify it is in working state and establish happens-before
}
assertTrue { caughtException is TestException }
executor.close()
}
}

0 comments on commit 00122c5

Please sign in to comment.