title: Thread.sleep() in While Loop
body: <p>There is a producer keeps generating files and put them into a special path. The consumer is a using <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html" rel="nofollow noreferrer">WatchService</a> to monitor the path and pick up any new generated files to work. Usually, the consumer's speed is slower than producer. In rare case, if the consumer finishes all the existing tasks and there is nothing new in the path yet, the consumer needs to hold on for a while.</p>
  <pre><code>while(true) {
      // do something...
      if(condition) {
          try {
              Thread.sleep(5000);
          } catch (InterruptedException e) {
              // handler
          }
      }
  }
  </code></pre>
  <p>IDE is complaining that <code>calling to Thread.sleep() in a while loop are indicative of &quot;busy-waiting&quot;. Busy-waiting is often inefficient, and may result in unexpected deadlocks as busy-waiting threads do not release locked resources</code>. Ignore this IDE warning will be my last option.</p>
  <p>How could I change my code to avoid the above warning architecture wise?</p>
  <p><em>(It seems a scheduled thread pool won't meet my requirement. Please correct me if I'm wrong.)</em></p>
  <p>Thanks for your comments and answers. Buffer events from WatchService to a blocking queue will work.</p>