Timeouts in Scala

In Scala, we can implement timeouts using Futures and the scala.concurrent.duration package. Here’s how we can translate the Go example:

import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

object Timeouts {
  def main(args: Array[String]): Unit = {
    // For our example, suppose we're executing an external
    // call that returns its result as a Future after 2s.
    val f1 = Future {
      Thread.sleep(2000)
      "result 1"
    }

    // Here we're implementing a timeout using `Await.result`.
    // It will wait for the Future to complete, but only for
    // the specified duration. If the Future doesn't complete
    // in time, it throws a TimeoutException.
    try {
      val result = Await.result(f1, 1.second)
      println(result)
    } catch {
      case _: java.util.concurrent.TimeoutException =>
        println("timeout 1")
    }

    // If we allow a longer timeout of 3s, then the Future
    // will complete successfully and we'll print the result.
    val f2 = Future {
      Thread.sleep(2000)
      "result 2"
    }

    try {
      val result = Await.result(f2, 3.seconds)
      println(result)
    } catch {
      case _: java.util.concurrent.TimeoutException =>
        println("timeout 2")
    }
  }
}

Running this program shows the first operation timing out and the second succeeding.

$ scala Timeouts.scala
timeout 1
result 2

In this Scala version:

  1. We use Futures to represent asynchronous computations.
  2. The Thread.sleep calls simulate long-running operations.
  3. We use Await.result to wait for a Future to complete, with a specified timeout.
  4. If the Future doesn’t complete within the timeout, a TimeoutException is thrown, which we catch and handle.

This approach provides similar functionality to the original example, allowing us to bound the execution time of operations and handle timeouts gracefully.