ciprianr
ciprianr

Reputation: 309

In which circumstances is Thread.sleep() the best approach for pausing a thread?

Thread.sleep() to me seems like a really useless concept because the only way I see it working is in the following scenarios

 public void someFunction()
 {
      //thread does something
      Thread.sleep(50000);
      //now other threads do something
 }

The problem is that for me this is just asking for trouble. I mean this can either be to long in which case at best you may have a performance issue and it may be too long and other threads may wait for the result in which case the situation may become critical.

I mean there are other way like using synchronized and wait which seem much more efficient.

So my question is, are there any situations where using thread sleep is the best option?

Upvotes: 3

Views: 1926

Answers (6)

Martin James
Martin James

Reputation: 24897

If the requirement spec calls for a five-second wait, maybe somewhere deep down in several functions in some process-control thread code, maybe only under some conditions, a Sleep(5000) call is a good solution for the following reasons:

  • It does not require simple in-line code to be rewritten as a complex state-machine so as to be able to use an asynchronous timer.

  • It invoves no other timer or pool thread to be run to implement the timeout.

  • It's a one-liner that does nor require wait-objects to be constructed etc.

  • Sleep() is available, in almost the same form, on all multitasking OS I have ever used.

Sleep() gets bad press because:

  • It 'wastes a thread'. In many systems, eg. when the thread is going to be there anyway and will run for the lifetime of the app, who cares?

  • It is often misused for inter-thread comms polling loops, so adding CPU waste and latency This is indeed indefensible.

  • It often cannot be interrupted so as to allow a 'clean and quick' shutdown of the thread. Again, in many systems, it does not matter if pool or app-lifetime threads get rudely stopped by a process termination, so why bother trying?

Example of reasonable usage:

void StartFeedstockDelivery{
  if (airbankPressure()<MIN_PRESSURE){
    startCompressor();
    sleep(10000);  // wait for pressure to build up
  openFeedValve();
};

Upvotes: 1

Marcin
Marcin

Reputation: 4323

You use Thread.sleep every time you want to slow things down. In certain scenarios you are unable to synchronize, like in case of communication with external systems over the network, database, etc.

Example scenarios:

  • Error recovery - When your system depends on some external entity that reports temporary errors. You communicate with external system you have no control of and it says it has temporary issues that are not related to your request. You do Thread.sleep and retry. If you did not sleep you would get error flood. This is quite common pattern in integration middleware.
  • Timeouts - You wait for something to happen but no longer than 10 seconds. You just cannot accept longer waits and want to quit.
  • Throttling - Someone tells you you cannot do something more often than once a 10 seconds.

Please keep in mind that there are various ways to wait, not neccessarily by calling Thread.sleep.

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136072

Both Thread.sleep(long) and Object.wait(long) block current thread. However wait may return earlier (spurious wakeup), see javadoc. So for wait we need to implement additional logic which guarantees that specified amount of time elapsed. So if you simply want to make a pause - use Thread.sleep

Upvotes: 2

user207421
user207421

Reputation: 311008

It would be impossible to write java.util.Timer without a sleep() method, or at least it would require you to abuse the wait() method, and write a lot of extra code around it to protect against spurious wakeups.

Upvotes: 6

Ardi Goxhaj
Ardi Goxhaj

Reputation: 382

Consider a service launching 2 different threads performing 2 different things connected to each other, one of the threads fails an an exception is caught(network problem, a remote host doesn't reply), you want your service to be up and running in the shortest time possible. The best thing is to wait some time and then to re-run your failing thread. You do not know when the remote host will be up you have to test the connection. In this case the best solution is to wait for some time and then to rerun your thread and not to re-run endlessly the failing thread (CPU load).

Upvotes: 2

Nick Louloudakis
Nick Louloudakis

Reputation: 6015

Although many times the event-driven model is the best way to "wait" for an action to occur, there are sometimes that you need to wait intentionally for a short amount of time and then make an action. A common case of this is a condition of sampling/polling data (from files, from the network etc) between some periods of time. In this case, you just want to "refresh" your data in a sense between time intervals.

For example, if you have an application that makes requests to a web service via the network, you might want to have a threat to perform this task periodically, having a "sleeping" behavior most of the time, but perform the service request task after some time, repeating this behavior again and again.

Upvotes: 2

Related Questions