1

I am looking for a way to interrupt a loop in Java without multithreading.

public class Foo{
    public Foo(){

    }
    public void bar(long timeLimit)  {

       long endTime = System.currentTimeMillis() + (timeLimit * 1000);

       while (System.currentTimeMillis() < endTime) {

           // Some really long and complicated computation

        }

     }        

 }

At the moment I realized that which various (System.currentTimeMillis() < timeLimit) calls to check during the computation if there is time left but I guess that eats up some time and I am also facing the problem that if a loop starts in time, the computation might not be done in time.

Amending the timeLimit (let's say only using 40 % of the time) accordingly also does not work, because I cannot predict how long some computations take.

Which options are there?

Laura
  • 163
  • 4
  • 1
    possible duplicate of [Java loop for a certain duration](http://stackoverflow.com/questions/2550536/java-loop-for-a-certain-duration) – nerdherd Jun 18 '14 at 20:24
  • 1
    why *without multithreading*? Do Actors and Futures count as multithreading? – rompetroll Jun 18 '14 at 20:50
  • @rompetroll: Multithreading is prohibited in my lab. This is because we compete with other teams for the best performance. I think Actors and Futures are implement with Threads, right? – Laura Jun 18 '14 at 21:10
  • 1
    OK, Actors and Futures would probably count as cheating then. You would need to create at least one new thread there. Unfortunately concurrency is the only way I can think of to do this properly. Even if you could split the complicated computation up into smaller chunks, so that you could check the time between the smaller steps in each iteration, you would still risk exceeding the time limit because one step still computes when the time is up... – rompetroll Jun 18 '14 at 21:19
  • 2
    Perhaps you can decompose the processing tasks sufficiently, then time each performed task to get an average running time per task, so that you can estimate whether you have enough time remaining to perform each remaining task before starting it. – JimN Jun 19 '14 at 02:43

0 Answers0