Goroutines in Scala

Based on the provided Go code example and the specified target language ‘Scala’, here’s the translated example along with an explanation:


A goroutine is a lightweight thread of execution.

object GoroutinesExample {
  def main(args: Array[String]): Unit = {
    def f(from: String): Unit = {
      for (i <- 0 until 3) {
        println(s"$from : $i")
      }
    }

    // Call the function synchronously
    f("direct")

    // To call a function concurrently, use a new thread.
    new Thread(new Runnable {
      def run(): Unit = {
        f("goroutine")
      }
    }).start()

    // You can also start a thread for an anonymous function call.
    new Thread(new Runnable {
      def run(): Unit = {
        println("going")
      }
    }).start()

    // Wait for the concurrent threads to finish
    Thread.sleep(1000)  // Sleep for 1 second
    println("done")
  }
}

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

f("direct")

To invoke this function in a new thread, use

new Thread(new Runnable {
  def run(): Unit = {
    f("goroutine")
  }
}).start()

This new thread will execute concurrently with the calling one.

You can also start a thread for an anonymous function call.

new Thread(new Runnable {
  def run(): Unit = {
    println("going")
  }
}).start()

Our two function calls are running asynchronously in separate threads now. Wait for them to finish with a sleep (for a more robust approach, use a CountDownLatch or similar synchronization primitive).

Thread.sleep(1000)  // Sleep for 1 second
println("done")

When we run this program, we see the output of the blocking call first, then the output of the two threads. The threads’ output may be interleaved because threads are being run concurrently by the runtime.

$ scala GoroutinesExample
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done

Next, we’ll look at a complement to concurrent programs: communication between threads using other mechanisms.