Skip to content

Commit 6543988

Browse files
qwwdfsadelizarov
authored andcommitted
Start lazy actor when calling close
Rationale: While it is possible to atomically transition state machine to "completed", it has multiple caveats: * It breaks intuition that "close" allows actors to process remaining messages and call its body * It introduces one more internal API dependency * It makes behaviour of non-lazy and lazy actors inconsistent Fixes #939
1 parent d8f005c commit 6543988

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

kotlinx-coroutines-core/jvm/src/channels/Actor.kt

+5
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,11 @@ private class LazyActorCoroutine<E>(
156156
return super.offer(element)
157157
}
158158

159+
override fun close(cause: Throwable?): Boolean {
160+
start()
161+
return super.close(cause)
162+
}
163+
159164
override val onSend: SelectClause2<E, SendChannel<E>>
160165
get() = this
161166

kotlinx-coroutines-core/jvm/test/channels/ActorLazyTest.kt

+18
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,22 @@ class ActorLazyTest : TestBase() {
6161
assertThat(actor.isClosedForSend, IsEqual(true))
6262
finish(6)
6363
}
64+
65+
@Test
66+
fun testCloseFreshActor() = runTest {
67+
val job = launch {
68+
expect(2)
69+
val actor = actor<Int>(start = CoroutineStart.LAZY) {
70+
expect(3)
71+
for (i in channel) { }
72+
expect(4)
73+
}
74+
75+
actor.close()
76+
}
77+
78+
expect(1)
79+
job.join()
80+
finish(5)
81+
}
6482
}

kotlinx-coroutines-core/jvm/test/channels/ActorTest.kt

+12
Original file line numberDiff line numberDiff line change
@@ -169,4 +169,16 @@ class ActorTest(private val capacity: Int) : TestBase() {
169169
parent.join()
170170
finish(2)
171171
}
172+
173+
@Test
174+
fun testCloseFreshActor() = runTest {
175+
for (start in CoroutineStart.values()) {
176+
val job = launch {
177+
val actor = actor<Int>(start = start) { for (i in channel) {} }
178+
actor.close()
179+
}
180+
181+
job.join()
182+
}
183+
}
172184
}

0 commit comments

Comments
 (0)