1

(Duplication: there are a lot of questions about wait() vs sleep(), but I need this specific detail, which I haven't found addressed in any on the answers.)

Context:

I have a scheduler implemented with sleep(), but I want to change its implementation to use wait(timeout) instead, so to have better control on "waking" it up, using notify() on a precise object instead of interrupt().

The main advantage is that the content code (which can contain other sleep()s, other wait()s, blocking I/O, etc., in the same thread, possibly from various libraries, etc.) doesn't have to ensure a given management of the interrupt. Notifying a specific object I'm sure to wake up only that specific wait() with absolutely no impact on other code in that thread.

Using wait(timeout) + notify() seems the best way to ensure not to disrupt any other code in the thread.

Only the scheduler thread and the thread possibly asking to wake up can contend the lock for that specific object, hence obtaining the lock should not be a tangible delay.

As for spurious wake-ups, I presume I can test the actually elapsed time and proceed to wait again if needed. (Which defends against "too little time suspended" but not against "too much time suspended", hence the question.)

Question:

Can I assume that, on any JVM or so, wait(timeout) is at least as precise as sleep(timeout), in suspending for timeout milliseconds, as precisely as possible?

Also, is the issue with "spurious wake-up" from wait() present also with sleep()?

In other words: to suspend for timeout milliseconds, have I any disadvantages in using a wait(timeout) instead of a sleep(timeout) apart for the following?

  • having to obtaining the lock (presumably negligible in the context)

  • defend against spurious wake-up (assuming sleep() is immune instead, confirm?)

Should I expect any degradation in scheduling precision?

Again, please note that the main goal is to wait timeout milliseconds, I'm using wait(timeout) as a sleep() that can be waked up in a more manageable way, without disrupting any other code in that thread.

GozzoMan
  • 782
  • 9
  • 23
  • 3
    Since the API documentation of both `Object.wait(int millis)` and `Thread.sleep(int millis)` doesn't describe it, there are no guarantees about how accurate the amount of time that the thread will wait is. – Jesper Mar 24 '15 at 14:23
  • @Jesper The question is about relative accuracy between the two. I.e. no absolute guarantee, but are the accuracy of the two the same? – GozzoMan Mar 24 '15 at 14:38
  • 2
    @GozzoMan And the answer is the same. The documentation doesn't mention such a guarantee => there is no guarantee. – user207421 Mar 24 '15 at 14:51

0 Answers0