File tree 2 files changed +63
-3
lines changed
kotlinx-coroutines-core/jvm
2 files changed +63
-3
lines changed Original file line number Diff line number Diff line change @@ -92,7 +92,7 @@ private class BlockingCoroutine<T>(
92
92
try {
93
93
while (true ) {
94
94
@Suppress(" DEPRECATION" )
95
- if (Thread .interrupted()) throw InterruptedException (). also { cancelCoroutine(it) }
95
+ if (Thread .interrupted()) cancelCoroutine( InterruptedException ())
96
96
val parkNanos = eventLoop?.processNextEvent() ? : Long .MAX_VALUE
97
97
// note: process next even may loose unpark flag, so check if completed before parking
98
98
if (isCompleted) break
Original file line number Diff line number Diff line change 1
1
package kotlinx.coroutines
2
2
3
3
import kotlinx.coroutines.testing.*
4
- import org.junit.*
4
+ import java.util.concurrent.CountDownLatch
5
+ import kotlin.concurrent.thread
6
+ import kotlin.test.*
7
+ import kotlin.time.Duration
5
8
6
9
class RunBlockingJvmTest : TestBase () {
7
10
@Test
@@ -12,5 +15,62 @@ class RunBlockingJvmTest : TestBase() {
12
15
}
13
16
rb.hashCode() // unused
14
17
}
15
- }
16
18
19
+ /* * Tests that the [runBlocking] coroutine runs to completion even it was interrupted. */
20
+ @Test
21
+ fun testFinishingWhenInterrupted () {
22
+ startInSeparateThreadAndInterrupt { mayInterrupt ->
23
+ expect(1 )
24
+ try {
25
+ runBlocking {
26
+ try {
27
+ mayInterrupt()
28
+ expect(2 )
29
+ delay(Duration .INFINITE )
30
+ } finally {
31
+ withContext(NonCancellable ) {
32
+ expect(3 )
33
+ repeat(10 ) { yield () }
34
+ expect(4 )
35
+ }
36
+ }
37
+ }
38
+ } catch (_: InterruptedException ) {
39
+ expect(5 )
40
+ }
41
+ }
42
+ finish(6 )
43
+ }
44
+
45
+ /* * Tests that [runBlocking] will exit if it gets interrupted. */
46
+ @Test
47
+ fun testCancellingWhenInterrupted () {
48
+ startInSeparateThreadAndInterrupt { mayInterrupt ->
49
+ expect(1 )
50
+ try {
51
+ runBlocking {
52
+ try {
53
+ mayInterrupt()
54
+ expect(2 )
55
+ delay(Duration .INFINITE )
56
+ } catch (_: CancellationException ) {
57
+ expect(3 )
58
+ }
59
+ }
60
+ } catch (_: InterruptedException ) {
61
+ expect(4 )
62
+ }
63
+ }
64
+ finish(5 )
65
+ }
66
+
67
+ private fun startInSeparateThreadAndInterrupt (action : (mayInterrupt: () -> Unit ) -> Unit ) {
68
+ val latch = CountDownLatch (1 )
69
+ val thread = thread {
70
+ action { latch.countDown() }
71
+ }
72
+ latch.await()
73
+ thread.interrupt()
74
+ thread.join()
75
+ }
76
+ }
You can’t perform that action at this time.
0 commit comments