0

I am calling a method in which there is loop which will end only if it find some results otherwise it keeps on looping until it find

public Collection<Serializable> searchItems(Collection<String> tags) {
    Collection<Serializable> answers = (Collection<Serializable>) 
        this.issueParallelOperation(tags, RemoteOperation.getIndex, 
        null, null, null, null, AggregationStrategy.joinCollection);
}

The code inside the method this.issueParallelOperation() keeps on looping until it find the result. I want to stop the operation after 1 min and set the answers value manually like null. I cant make changes inside this.issueParallelOperation() method as it is called by many other methods. Can anyone please suggest me some ideas how to solve this issue in this searchItems() method

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Acjb
  • 505
  • 1
  • 6
  • 21
  • Can you provide the definition for the issueParallelOperation method (or the code)? Usually the modern paradigm is to provide a method call that requests termination (rather than killing a thread). You should also probaly invoke this call in a separate thread so you can make such a "stop" request. – ErstwhileIII Feb 25 '14 at 13:08

1 Answers1

0

You can record the start time of the function, and then check the current time against the start time and your duration whenever you loop. Something like:

public Object functionWithTimeout(long duration){
   long start = System.currentTimeMillis();

   while(someCriteria){
      if(System.currentTimeMillis() - start > duration){
         //the function has timed out
         break;
      }

      //whatever code you want to repeat until the timeout
   }

   return null;
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107