Time Limited Loop in Java

Executing a loop in a given time duration is a challanging question that I' ve found at StackOverFlow. There are many solutions offered by SOF posters. The asker's wish is as follows; but implementation is just a little bit more complex than what he thinks.

int x = 0;
for( 2 minutes )  {
   System.out.println(x++);
}

My solution is implementing a stopper thread in an inner class that will sleep for intended duration, then invokes setStop(true) method of the class to break the condition of loop. To succeed in this, the condition of the time limited loop must depend on "isStop()" method.

// The loop will stop in 2 sec.
StopperThread stopperThread = new StopperThread(2000);
//if isStop returns true, then the next check of condition 
//will break the loop.
while (index < limit && !isStop()) {
 System.out.println("#Did sth: " + index);
 index += increment;
}

Stopper thread is implemented in order to sleep in a given time as constructor parameter. If it is interrupted, it must sleep in remaining time. The InterruptedException catch clause is calculating the remaining time then update the sleep time. Stopper thread is as follows:

class StopperThread extends Thread {
 private long time = 0; 
 public StopperThread(long time) {
  this.time = time;
 }
  
 @Override
 public void run() {
  long startAt=0;
     
  while(true) {
   startAt = System.currentTimeMillis();
   try {
    Thread.sleep(this.time);
   }catch (InterruptedException e) {
    this.time -= (System.currentTimeMillis() - startAt);
    if(this.time > 0)
     continue; 
   }
   setStop(true);
   break;
  }
 }
}

Download Source
Download as PDF

Join 4Shared Now!

Comments

Post a Comment

Thx for reading! Comments are appreciated...

Popular posts from this blog

SoapUI 4.5.0 Project XML File Encoding Problem

COMRESET failed (errno=-32)

SoapUI - Dynamic Properties - Getting Current Time in DateTime Format