title: How to have an efficient loop in a thread
body: <p>I am calling some service that returns a response thru some callback function.
  I used thread to call this service so that it is running in its own process.
  The thread is called in my Main thread.</p>
  
  <p>My question is how can I optimize my busy while loop in calling this service.
  Sometimes the service fails and it is okay to just continue to retry looping in until a good response is received.</p>
  
  <pre><code>public class ProcessResponse extends Thread
      boolean isOK = false;
  
      public void responseReturned(Response response){
          //more code
          if(response.OK){
              //process result
              isOK = true; 
          }
      }
  
      public void run(){
          while(true){
              // call service
              Thread.sleep(1000);
              if(isOK)
                  break;
          }
      }
  }
  </code></pre>
  
  <p><strong>UPDATE 2:</strong>
  My next line of thinking is just to use latch</p>
  
  <pre><code>public class ProcessResponse extends Thread
      boolean isOK = false;
      CountDownLatch latch = new CountDownLatch(1);
  
  
      public void responseReturned(Response response){
          //more code
          if(response.OK){
              //process result
              isOK = true;
          }
          latch.countDown();
      }
  
      public void run(){
          while(!isOK){
              // call service
  
              try {
                  latch.await();
              } catch (InterruptedException e) {
                  //handle interruption
              }
              latch = new CountDownLatch(1);
          }
      }
  }
  </code></pre>
  
  <p>There is no sleep command but I am not sure if reinitializing the latch is a good approach.  The service sometimes takes time to return.
  Note..I haven't tried this code yet.. I just type it in so I am not sure if this will work.</p>