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:
So: why is Thread.sleep so inefficient compared to TimerTask?
The common reason for high CPU usage is loop in the code. It could be a loop in the user application or CICS code. Possible causes of a loop that does not terminate are: The termination condition can never occur.
Peripheral causes of high Java CPU usagepoorly configured Java GC; issues more correctly attributable to the software stack; thread synchronization, contention and deadlock issues; and. underlying file and database I/O problems.
Timer and TimerTask are java util classes that we use to schedule tasks in a background thread. Basically, TimerTask is the task to perform, and Timer is the scheduler.
TimerTask is an abstract class defined in java. util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With