I wrote a daemon which was structured like this:
while( true ) {
// do some stuff
Thread.sleep( 1000 );
}
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.
Yesterday I refactored the code to use TimerTask. 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:


A couple of points:
- There is absolutely nothing else running on the production server except the JVM.
- There are no other application threads running
- It was definitely executing the old-style code at the correct periodic intervals – I always write to the log each time the thread executes.
So: why is Thread.sleep so inefficient compared to TimerTask?
Three possibilities I can think of:
continue;statement somewhere in your loop before the sleep, so even if the main body of work of the loop isn’t executing very frequently, something is. It’s hard to say without seeing some more concrete code though.A simple loop just executing
Thread.sleep(1000)repeatedly should be very cheap – and that should be easy for you to verify, too.