Johnny
Johnny

Reputation: 15413

Running a block with a timeout in Scala without using Futures?

Is there a way to running a function with a timeout in Scala, without Futures?

For example, something like:

val result = runWithTimeout (timeout, function}

The reason to avoid Future, is because we work in a complex running environment and I would like to avoid spanning the threads and managing ExecutionContext.

Upvotes: 0

Views: 319

Answers (1)

Johnny
Johnny

Reputation: 15413

In general it's not possible in JVM without applying some effect system like cats-effect, fs2, monix or Zio.

We need to have another thread to trigger the time timeout. Another issue, is when you calling with runWithTimeout(Thread.sleep(1 hours)), it will release the caller thread but it will eat the thread from the thread pool for 1 hour.

Still, to go this way, you can do something like:

object Execution {

  def runWithTimeout[T](timeout: Duration)(f: => T)(implicit ec: ExecutionContext): Option[T] = {
    try {
      Some(Await.result(Future(f), timeout))
    } catch {
      case e: TimeoutException => None
    }
  }
}

Upvotes: 1

Related Questions