fcw
fcw

Reputation: 259

Java performance issue with Thread.sleep()

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?

Upvotes: 23

Views: 22889

Answers (8)

BJYC
BJYC

Reputation: 394

It might NOT be a problem, it depends.

In my case, I use Thread.sleep() to wait for a couple of seconds before another reconnect attempt to an external process. I have a while loop for this reconnect logic till it reaches the max # of attemps. So in my case, Thread.sleep() is purely for timing purpose and not coordinating among multithreads, it's perfectly fine.

You can configure you IDE in how this warning should be handled.

Upvotes: 1

Adrian
Adrian

Reputation: 31

http://www.jsresources.org/faq_performance.html

1.6. What precision can I expect from Thread.sleep()?

The fundamental problem with short sleeps is that a call to sleep finishes the current scheduling time slice. Only after all other threads/process finished, the call can return.

For the Sun JDK, Thread.sleep(1) is reported to be quite precise on Windows. For Linux, it depends on the timer interrupt of the kernel. If the kernel is compiled with HZ=1000 (the default on alpha), the precision is reported to be good. For HZ=100 (the default on x86) it typically sleeps for 20 ms.

Using Thread.sleep(millis, nanos) doesn't improve the results. In the Sun JDK, the nanosecond value is just rounded to the nearest millisecond. (Matthias)

Upvotes: 3

Rulix Batistil
Rulix Batistil

Reputation: 231

I have face this problem before when waiting for asynchronous process to return a result.

Thread.sleep is a problem on multi thread scenario. It tends to oversleep. This is because internally it rearrange its priority and yields to other long running processes (thread).

A new approach is using ScheduledExecutorService interface or the ScheduledThreadPoolExecutor introduce in java 5.

Reference: http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html

Upvotes: 1

test
test

Reputation: 21

why? that is because of context switching (part of the OS CPU scheduling)

How? calling Thread.sleep(t) makes the current thread to be moved from the running queue to the waiting queue. After the time 't' reached the the current thread get moved from the waiting queue to the ready queue and then it takes some time to be picked by the CPU and be running.

Solution: call Thread.sleep(t*10); instead of calling Thread.Sleep(t) inside loop of 10 iterations ...

Upvotes: 2

Ivan
Ivan

Reputation: 1256

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".

Upvotes: 0

Chris Dennett
Chris Dennett

Reputation: 22741

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.

Upvotes: 6

Brad Mace
Brad Mace

Reputation: 27906

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()

Upvotes: 5

Thilo
Thilo

Reputation: 262814

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).

Upvotes: 36

Related Questions