18

Do spurious wakeups affect calls to Thread.sleep(x)?

Obviously, the timer is not 100% precise (leading to minor inaccuracies in wakeup times), but is it affected by the spurious wakeup problem?

Lii
  • 11,553
  • 8
  • 64
  • 88
jsight
  • 27,819
  • 25
  • 107
  • 140
  • What do you mean by 'affected'? Are you asking if it can cause them to not execute at the proper time? or not wake up? Or are you asking if they can wake up accidentally? – Kylar Mar 05 '10 at 18:08
  • I'm asking if they can be woken up accidentally before they should be woken up (with "should be" being defined as a length of time greater than the natural inaccuracy of the underlying timer). – jsight Mar 05 '10 at 18:12

2 Answers2

10

You're asking whether Thread.sleep() is affected by the same spurious wakeup issue that is documented to affect Object.wait(long), right? The answer is that there is no documented spurious wakeup associated with Thread.sleep(). You're right that no hard guarantees are made about exactly how long you'll sleep when you request N milliseconds. Also, of course, Thread.sleep() terminates on thread interrupt.

Jonathan Feinberg
  • 44,698
  • 7
  • 80
  • 103
  • 8
    So do you mean the answer is "No, we do not have to guard against spurious wakeup" or "Yes, we do have to guard against spurious wakeup" ? – Pacerier Dec 08 '11 at 14:58
  • @Pacerier: I would summarise (or rephase) as: `Thread.sleep()` does not suffer from spurious wake-ups. (The official JDK docs make no mention of spurious wake-ups for `Thread.sleep()`) However, `Thread.sleep()` is not guaranteed to sleep `x` milliseconds, as another thread may call `Thread.interrupt()` to wake-up the sleeping thread. – kevinarpe Jan 04 '21 at 09:11
5

real interval of sleep is always >= required interval. it is especially sensitive on small intervals.

now about "spurious wakeups". it was not mentioned about Thread.sleep

Andrey
  • 59,039
  • 12
  • 119
  • 163