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

1
  • 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. Commented Feb 25, 2014 at 13:08

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Requires original method change.
Ah, I didn't catch that the OP couldn't change the original method. I'll leave the answer for now, for people who can change the original method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.