netflux
netflux

Reputation: 3838

Why did switching to from an infinite loop to TimerTask cause this drop in CPU usage?

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:

Load average

CPU usage

A couple of points:

So: why is Thread.sleep so inefficient compared to TimerTask?

Upvotes: 11

Views: 1717

Answers (2)

Lealo
Lealo

Reputation: 321

Compare the speed of your processor, a thread and a timertask. The timertask is a slower thread (much slower).

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500625

Three possibilities I can think of:

  • You have a huge number of threads doing this, and they're context switching all the time. Using a timer will mean there's only one thread instead. On the other hand, that means you will only get one task executing at a time.
  • You have a 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.
  • You have a broken JVM/OS combination. This seems pretty unlikely, admittedly.

A simple loop just executing Thread.sleep(1000) repeatedly should be very cheap - and that should be easy for you to verify, too.

Upvotes: 11

Related Questions