views:

712

answers:

1

Has anyone observed that creating a thread that does work in a while(true) loop with a Thread.sleep(t) appears to consume more CPU than creating a Timer in Java with a wakeup of t? Anyone with JVM expertise know why this is? I've only really tried this on Windows and Linux x86.

+1  A: 

According to the Javadoc for the Timer class, there's a background thread that does the work:

Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. Timer tasks should complete quickly. If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.

How are you observing CPU usage? Have you tried a JVM profiler?

atc
I'm not - although I can try using JConsole or VisualVM. I was simply using TaskManager in windows on a quiet machine.
Amir Afghani
I'd be very weary of what that's reporting - it's by no means a definitive profiling tool.Have a look at using VisualVM for profiling your app as it will give you a lot more detail.
atc