Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computation with time limit

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

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

val result: Option[Double] = timeLimited( 45 ) { expensiveComputation() }

Here the timeLimited will run expensiveComputation with a timeout of 45 minutes. If it reaches the timeout it returns None, else it wrapped the result into Some.

I am looking for a solution which:

  • Is pretty cheap in performance and memory;
  • Will run the time-limited task in the current thread.

Any suggestion ?

EDIT

I understand my original problem has no solution. Say I can create a thread for the calculation (but I prefer not using a threadpool/executor/dispatcher). What's the fastest, safest and cleanest way to do it ?

like image 571
paradigmatic Avatar asked Oct 04 '11 16:10

paradigmatic


3 Answers

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)
}
like image 180
gruenewa Avatar answered Nov 13 '22 05:11

gruenewa


Only an idea: I am not so familiar with akka futures. But perhaps its possible to stick the future executing thread to the current thread and use akka futures with timeouts?

like image 3
Peter Schmitz Avatar answered Nov 13 '22 05:11

Peter Schmitz


To the best of my knowledge, either you yield (the computation calls to some scheduler) or you use a thread, which gets manipulated from the "outside".

like image 2
ziggystar Avatar answered Nov 13 '22 05:11

ziggystar