Time limited calculation

I am trying to write a construct that allows me to run calculations in a given time window. Something like:

def expensiveComputation(): Double = //... some intensive math val result: Option[Double] = timeLimited( 45 ) { expensiveComputation() } 

Here timeLimited will run expensiveComputation with a timeout of 45 minutes. If it reaches a timeout, it returns None , otherwise it completes the result in Some .

I am looking for a solution that:

  • Very cheap in performance and memory;
  • Runs a time-limited task in the current thread .

Any suggestion?

EDIT

I understand that my original problem has no solution. Say I can create a thread for computation (but I prefer not to use threadpool / executor / dispatcher). What is the fastest, safest and cleanest way to do this?

+8
java scala timeout
source share
9 answers

Runs this block of code or throws an exception in 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) } 
+8
source share

Just an idea: I am not so familiar with akka futures . But, perhaps, it can be tied to the future execution of the stream to the current stream and use akka futures with timeouts?

+3
source share

As far as I know, you give (call calculations for some kind of scheduler) or you use a thread that is processed from "outside".

+2
source share

If you want to run the task in the current thread, and if there should not be other threads, you will need to check if the deadline in expensiveComputation exceeds. For example, if expensiveComputation is a loop, you can check the time after each iteration.

+1
source share

If you know the expensiveComputation code to check Thread.interrupted() , it's pretty easy. But I suppose not.

I don't think there is any solution that would work for arbitrary expensiveComputation arbitrary code. The question is what are you willing to have as a limitation for costly computing.

You have an outdated and rather insecure Thead.stop(Throwable) too. If your code does not modify any object other than those that it created on its own, it may work.

+1
source share

I saw a template similar to this job for time-limited tasks (Java code):

 try { setTimeout(45*60*1000); // 45 min in ms while (not done) { checkTimeout(); // do some stuff // if the stuff can take long, again: checkTimeout(); // do some more stuff } return Some(result); } catch (TimeoutException ex) { return None; } 

The checkTimeout() function is cheap to call; you add it to the code to be called often enough, but not too often. All he does is check the current time for the timer value set to setTimeout() plus the timeout value. If the current time exceeds this value, checkTimeout() raises a TimeoutException .

I hope this logic can be reproduced in Scala as well.

+1
source share

For a general solution (without having to iterate over each of your expensive Computations with checkTimeout () code), perhaps use a Javassist. http://www.csg.is.titech.ac.jp/~chiba/javassist/
Then you can dynamically insert various checkTimeout () methods.
Here is the opening text on your website:

Javassist (Java Programming Assistant) simplifies Java bytecode manipulation. This is a class library for editing bytecodes in Java; it allows Java programs to define a new class at run time and modify the class file when the JVM loads it. Unlike other similar bytecode editors, Javassist provides two levels of API: source level and bytecode level. If users use the source level API, they can edit the class file without knowing the Java bytecode specifications. All API is developed only with vocabulary of the Java language. You can even specify the inserted bytecode as source text; Javassist compiles it on the fly. The bytecode level API, on the other hand, allows users to directly edit the class file like other editors.

Aspect Oriented Programming: Javassist can be a good tool for adding new methods to a class and for inserting tips before / after / around both the caller side and the caller side.

Reflection: One of the Javassist applications is runtime reflection; Javassist allows Java programs to use a meta object that manages method calls on base-level objects. No specialized compiler or virtual machine is needed.

+1
source share

In currentThread ?? Phhhew ... Verification after each step of the calculation Well, if your "expensive calculation" can be divided into several stages or have iterative logic, you can capture the time when you start, and then periodically check between steps. This is by no means a general solution, but it will work.

For a more general solution, you can use aspects or annotation processing that automatically puts your code with these checks. If the β€œcheck” tells you that your time is not returning, then no.

Think of a solution in java quickly using annotations and an annotation handler ...

 public abstract Answer{} public class Some extends Answer {public Answer(double answer){answer=answer}Double answer = null;} public class None extends Answer {} //This is the method before annotation processing @TimeLimit(45) public Answer CalculateQuestionToAnswerOf42() { double fairydust = Math.Pi * 1.618; double moonshadowdrops = (222.21) ^5; double thedevil == 222*3; return new Answer(fairydust + moonshadowdrops + thedevil); } //After annotation processing public Answer calculateQuestionToAnswerOf42() { Date start = new Date() // added via annotation processing; double fairydust = Math.Pi * 1.618; if(checkTimeout(start, 45)) return None; // added via annotation processing; double moonshadowdrops = (222.21) ^5; if(checkTimeout(start, 45)) return None; // added via annotation processing; double thedevil == 222*3; if(checkTimeout(start, 45)) return None; // added via annotation processing; return new Answer(fairydust + moonshadowdrops + thedevil); } 
0
source share

If you really need this, you can create a compiler plugin that inserts check blocks into loops and conditions. These control blocks can then check Thread.isInterrupted () and throw an exception.

You can use annotation, i.e. @interruptible, to mark improvement methods.

0
source share

All Articles