title: NetBeans / Java / New hint: Thread.sleep called in loop
body: <p>In NetBeans, there's a new hint that says: <strong>Thread.sleep called in loop.</strong></p>
  
  <p><strong>Question 1:</strong> How/when can it be a problem to sleep in a loop?</p>
  
  <p><strong>Question 2:</strong> If it's a problem, what should I do instead?</p>
  
  <p><strong>UPDATE: Question 3:</strong> Here's some code. Tell me in this case if I should be using something else instead of Thread.Sleep in a loop. In short, this is used by a server which listens for client TCP connections. The sleep is used here in case the max number of sessions with clients is reached. In this situation, I want the application to wait until a free session becomes available.</p>
  
  <pre><code>public class SessionManager {
      private static final int DEFAULT_PORT = 7500;
      private static final int SLEEP_TIME = 200;
      private final DatabaseManager database = new DatabaseManager();
      private final ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT);
  
  public SessionManager() throws IOException, SQLException
  {
  }
  
  public void listen()
  {
  while (true)
      if (Session.getSessionCount() &lt; Session.getMaxSessionCount())
          try
          {
               new Thread(new Session(database, serverSocket.accept())).start();
          }
          catch (IOException ex) { ex.printStackTrace(); }
      else
          try
          {
              Thread.sleep(SLEEP_TIME);
          }
          catch (InterruptedException ex) { ex.printStackTrace(); }
  }
  
  public static void main(String[] args) throws IOException, SQLException
  {
  new SessionManager().listen();
  }
  }
  </code></pre>