Skip to content

Commit a79a5cb

Browse files
committed
Do not react to interruptions in runBlocking before first suspension
1 parent 133ed42 commit a79a5cb

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

kotlinx-coroutines-core/jvm/src/Builders.kt

+1-2
Original file line numberDiff line numberDiff line change
@@ -91,12 +91,11 @@ private class BlockingCoroutine<T>(
9191
eventLoop?.incrementUseCount()
9292
try {
9393
while (true) {
94-
@Suppress("DEPRECATION")
95-
if (Thread.interrupted()) cancelCoroutine(InterruptedException())
9694
val parkNanos = eventLoop?.processNextEvent() ?: Long.MAX_VALUE
9795
// note: process next even may loose unpark flag, so check if completed before parking
9896
if (isCompleted) break
9997
parkNanos(this, parkNanos)
98+
if (Thread.interrupted()) cancelCoroutine(InterruptedException())
10099
}
101100
} finally { // paranoia
102101
eventLoop?.decrementUseCount()

kotlinx-coroutines-core/jvm/test/RunBlockingJvmTest.kt

+28
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,23 @@ class RunBlockingJvmTest : TestBase() {
6565
finish(5)
6666
}
6767

68+
/** Tests that [runBlocking] does not check for interruptions before the first attempt to suspend,
69+
* as no blocking actually happens. */
70+
@Test
71+
fun testInitialPortionRunningDespiteInterruptions() {
72+
Thread.currentThread().interrupt()
73+
runBlocking {
74+
expect(1)
75+
try {
76+
Thread.sleep(Long.MAX_VALUE)
77+
} catch (_: InterruptedException) {
78+
expect(2)
79+
}
80+
}
81+
assertFalse(Thread.interrupted())
82+
finish(3)
83+
}
84+
6885
/**
6986
* Tests that [runBlockingNonInterruptible] is going to run its job to completion even if it gets interrupted
7087
* or if thread switches occur.
@@ -138,6 +155,17 @@ class RunBlockingJvmTest : TestBase() {
138155
finish(3)
139156
}
140157

158+
/**
159+
* Tests that starting [runBlockingNonInterruptible] in an interrupted thread does not affect the result.
160+
*/
161+
@Test
162+
fun testNonInterruptibleRunBlockingStartingInterrupted() {
163+
Thread.currentThread().interrupt()
164+
val v = runBlockingNonInterruptible { 42 }
165+
assertEquals(42, v)
166+
assertTrue(Thread.interrupted())
167+
}
168+
141169
private fun startInSeparateThreadAndInterrupt(action: (mayInterrupt: () -> Unit) -> Unit) {
142170
val latch = CountDownLatch(1)
143171
val thread = thread {

0 commit comments

Comments
 (0)