Channel close vs channel receive

In the following scenario:

        runBlocking(Dispatchers.IO) {
            val channel = Channel<String>()
            launch {
                channel.send("Hello World")
                channel.close()
            }
            println(channel.recive())
        }

Is it guaranteed that it always prints “Hello World”? In other words, is it possible that channel was closed before “channel.receive()” is called?

Is the answer the same for this case:

        runBlocking(Dispatchers.IO) {
            val channel = Channel<String>()
            launch {
                println(channel.recive())
            }
            launch {
                channel.send("Hello World")
                channel.close()
            }
        }

?

Cheers, Jacek.

In this specific case it is guaranteed close() happens after receive(), because the channel is RENDEZVOUS, so send() suspends until receiving. If the channel would have a buffer, the order would not be guaranteed. But… it doesn’t really matter, because you still can receive items from a closed channel. You can’t send to it.

1 Like

Right, I sanitized my code too much. In real I do actually have a buffer

val channel = Channel<String>(1)

The docs say:

fun close()
Closes this channel. (…)
Immediately after invocation of this function, isClosedForSend starts returning true. However, isClosedForReceive on the side of ReceiveChannel starts returning true only after all previously sent elements are received.

The bolded part is what I missed, I thought that both properties start to return true after close(). Thanks :slight_smile: