title: Why did switching to from an infinite loop to TimerTask cause this drop in CPU usage?
body: <p>I wrote a daemon which was structured like this:</p>
  
  <pre><code>while( true ) {
    // do some stuff
    Thread.sleep( 1000 );
  }
  </code></pre>
  
  <p>I noticed it was using a very large amount of CPU - up to 100%. I have had a similar daemon on my production servers for some months with the same CPU problem.</p>
  
  <p>Yesterday I refactored the code to use <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/util/TimerTask.html" rel="noreferrer">TimerTask</a>. Immediately I noticed that CPU usage had decreased on my dev box. So I decided to deploy to production and double-check using Munin. Here are the graphs:</p>
  
  <p><img src="https://i.stack.imgur.com/g67XA.png" alt="Load average"></p>
  
  <p><img src="https://i.stack.imgur.com/X9evS.png" alt="CPU usage"></p>
  
  <p>A couple of points:</p>
  
  <ul>
  <li>There is absolutely nothing else running on the production server except the JVM.</li>
  <li>There are no other application threads running</li>
  <li>It was definitely executing the old-style code at the correct periodic intervals - I always write to the log each time the thread executes.</li>
  </ul>
  
  <p>So: why is Thread.sleep so inefficient compared to TimerTask?</p>