Channel default is: Unbuffered and Rendezvous (Blocks sender until Receive)

The default capacity of channel is called RENDEZVOUS

public fun <E> Channel(capacity: Int = RENDEZVOUS,...)

RENDEZVOUS is defined as a meeting at an agreed time and place, typically between two people. - google defintion.

Unbuffered channels transfer elements when sender and receiver meet each other (aka rendezvous). If send is invoked first, then it is suspended until receive is invoked, if receive is invoked first, it is suspended until send is invoked. - kotlin-doc


In Rendezvous Setting: Sender will get blocked until Receiver picks up the message.

In Action

Code

fun main(args: Array<String>) {
  runBlocking {
    // Default capacity of Channel is:
    //
    // capacity: Int = RENDEZVOUS,
    val channel = Channel<Int>()

    val sender = launch(CoroutineName("${Emoji.LETTER}-sender")) {
      repeat(2) {
        delay(100)

        out.info("starting_to_send: $it")
        channel.send(it)
        // Notice:
        // - in first message that sent is not going to be let go until it is received.
        // - second message we never get out of send as nobody is listening for 2nd receive.
        out.info("sent: $it")
      }
    }

    val listener = launch(CoroutineName("${Emoji.MAILBOX}-listener")) {
      repeat(1) {
        delay(500)

        out.info("received: ${channel.receive()}")
      }
    }

    delay(3000)
    listener.cancel()
    sender.cancel()
    out.info("Main completed")
  }
}

Command to reproduce:

gt.sandbox.checkout.commit 3f134b24cc26858fe8c6 \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run --quiet"

Recorded output of command:

[elapsed:  152ms][coroutine:✉️-sender] starting_to_send: 0
[elapsed:  543ms][coroutine:📬-listener] received: 0
[elapsed:  545ms][coroutine:✉️-sender] sent: 0
[elapsed:  649ms][coroutine:✉️-sender] starting_to_send: 1
[elapsed: 3040ms][coroutine:unnamed] Main completed

Backlinks