Computation with time limit

后端 未结 9 2395
你的背包
你的背包 2021-01-02 12:08

I\'m trying to write a construct which allows me to run computations in a given time window. Something like:

def expensiveComputation(): Double = //... some          


        
9条回答
  •  清歌不尽
    2021-01-02 12:52

    Runs the given code block or throws an exception on timeout:

    @throws(classOf[java.util.concurrent.TimeoutException])
    def timedRun[F](timeout: Long)(f: => F): F = {
    
      import java.util.concurrent.{Callable, FutureTask, TimeUnit}
    
      val task = new FutureTask(new Callable[F]() {
        def call() = f
      })
    
      new Thread(task).start() 
    
      task.get(timeout, TimeUnit.MILLISECONDS)
    }
    

提交回复
热议问题