11

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:

  • 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?

4

2 に答える 2

11

私が考えることができる3つの可能性:

  • これを行うスレッドは非常に多く、常にコンテキストを切り替えています。タイマーを使用すると、代わりにスレッドが1 つしかないことになります。一方、これは一度に 1 つのタスクしか実行できないことを意味します。
  • スリープ前のループのどこかにステートメントがあるcontinue;ため、ループの作業の本体が頻繁に実行されていなくても、何かが実行されています。ただし、より具体的なコードを見ずに言うのは難しいです。
  • JVM/OS の組み合わせが壊れています。確かに、これはかなりありそうにないようです。

繰り返し実行するだけの単純なループThread.sleep(1000)は、非常にコストがかからず、検証も簡単です。

于 2012-01-08T08:45:26.053 に答える