views:

837

answers:

4

Inline Java IDE hint states, "Invoking Thread.sleep in loop can cause performance problems." I can find no elucidation elsewhere in the docs re. this statement.

Why? How? What other method might there be to delay execution of a thread?

+5  A: 

It depends on whether the wait is dependent on another thread completing work, in which case you should use guarded blocks, or high level concurrency classes introduced in Java 1.6. I recently had to fix some CircularByteBuffer code that used Thread sleeps instead of guarded blocks. With the previous method, there was no way to ensure proper concurrency. If you just want the thread to sleep as a game might, in the core game loop to pause execution for a certain amount of time so that over threads have good period in which to execute, Thread.sleep(..) is perfectly fine.

Chris Dennett
+12  A: 

It is not that Thread.sleep in a loop itself is a performance problem, but it is usually a hint that you are doing something wrong.

while(! goodToGoOnNow()) {
   Thread.sleep(1000);
}

Use Thread.sleep only if you want to suspend your thread for a certain amount of time. Do not use it if you want to wait for a certain condition.

For this situation, you should use wait/notify instead or some of the constructs in the concurrency utils packages.

Polling with Thread.sleep should be used only when waiting for conditions external to the current JVM (for example waiting until another process has written a file).

Thilo
Thanks for the replies. The thread is communicating via TCP to an external piece of gear, waiting for it to start running:
fcw
The protocol is, Are you running? No. Sleep..... Are you running? No. Sleep... Are you running? Yes. Continue.... So no issue. Thx!
fcw
+4  A: 

It depends on why you're putting it to sleep and how often you run it.

I can think of several alternatives that could apply in different situations:

  • Let the thread die and start a new one later (creating threads can be expensive too)
  • Use Thread.join() to wait for another thread to die
  • Use Thread.yield() to allow another thread to run
  • Let the thread run but set it to a lower priority
  • Use wait() and notify()
bemace
A: 

I suggest looking into the CountDownLatch class. There are quite a few trivial examples out there online. Back when I just started multithreaded programming they were just the ticket for replacing a "sleeping while loop".

Ivan