Thread.sleep() in a while loop

2020-08-09 06:19发布

问题:

I notice that NetBeans is warning me about using Thread.sleep() in a while loop in my Java code, so I've done some research on the subject. It seems primarily the issue is one of performance, where your while condition may become true while the counter is still sleeping, thus wasting wall-clock time as you wait for the next iteration. This all makes perfect sense.

My application has a need to contact a remote system and periodically poll for the state of an operation, waiting until the operation is complete before sending the next request. At the moment the code logically does this:

String state = get state via RPC call
while (!state.equals("complete")) {
    Thread.sleep(10000); // Wait 10 seconds
    state = {update state via RPC call}
}

Given that the circumstance is checking a remote operation (which is a somewhat expensive process, in that it runs for several seconds), is this a valid use of Thread.sleep() in a while loop? Is there a better way to structure this logic? I've seen some examples where I could use a Timer class, but I fail to see the benefit, as it still seems to boil down to the same straightforward logic above, but with a lot more complexity thrown in.

Bear in mind that the remote system in this case is neither under my direct control, nor is it written in Java, so changing that end to be more "cooperative" in this scenario is not an option. My only option for updating my application's value for state is to create and send an XML message, receive a response, parse it, and then extract the piece of information I need.

Any suggestions or comments would be most welcome.

回答1:

Unless your remote system can issue an event or otherwise notify you asynchronously, I don't think the above is at all unreasonable. You need to balance your sleep() time vs. the time/load that the RPC call makes, but I think that's the only issue and the above doesn't seem of concern at all.



回答2:

Without being able to change the remote end to provide a "push" notification that it is done with its long-running process, that's about as well as you're going to be able to do. As long as the Thread.sleep time is long compared to the cost of polling, you should be OK.



回答3:

You should (almost) never use sleep since its very inefficient and its not a good practice. Always use locks and condition variables where threads signal each other. See Mike Dahlin's Coding Standards for Programming with threads

A template is:

public class Foo{
  private Lock lock;
  private Condition c1;
  private Condition c2;

  public Foo()
  {
    lock = new SimpleLock();
    c1 = lock.newCondition();
    c2 = lock.newCondition();
    ...
  }

  public void doIt()
  {
    try{
      lock.lock();
      ...
      while(...){
        c1.awaitUninterruptibly();
      }
      ...
      c2.signal();
    }
    finally{
      lock.unlock();
    }
  }
}