Channel Synchronization in Kotlin

In Kotlin, we can use coroutines to achieve similar functionality to Go’s goroutines for concurrent execution. Here’s an example of using a channel (implemented as a Channel from kotlinx.coroutines) to synchronize execution across coroutines:

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel

// This is the function we'll run in a coroutine. The
// `done` channel will be used to notify another
// coroutine that this function's work is done.
suspend fun worker(done: Channel<Boolean>) {
    print("working...")
    delay(1000) // Simulate work
    println("done")

    // Send a value to notify that we're done.
    done.send(true)
}

fun main() = runBlocking {
    // Start a worker coroutine, giving it the channel to
    // notify on.
    val done = Channel<Boolean>()
    launch { worker(done) }

    // Block until we receive a notification from the
    // worker on the channel.
    done.receive()
}

To run this program:

$ kotlinc -cp kotlinx-coroutines-core-1.5.2.jar channel-synchronization.kt -include-runtime -d channel-synchronization.jar
$ java -jar channel-synchronization.jar
working...done

In this Kotlin version:

  1. We use suspend fun to define our worker function, which can be suspended and resumed.

  2. Instead of Go’s time.Sleep, we use Kotlin’s delay function for suspending the coroutine.

  3. We create a Channel<Boolean> instead of a Go channel.

  4. The go keyword is replaced by launching a new coroutine with launch { ... }.

  5. The main function is wrapped in runBlocking, which creates a coroutine and blocks the current thread until all launched coroutines complete.

  6. We use done.send(true) to send a value to the channel and done.receive() to receive from it.

If you removed the done.receive() line from this program, the program would exit before the worker even started, similar to the Go version.

Note: This example requires the kotlinx-coroutines-core library. Make sure to include it in your project dependencies.