Java's Object.wait method with nanoseconds: Is this a joke or am I missing something

Posted by Krumia on Programmers See other posts from Programmers or by Krumia
Published on 2014-08-12T12:02:19Z Indexed on 2014/08/24 22:32 UTC
Read the original article Hit count: 237

Filed under:

I was checking out the Java API source code (Java 8) just out of curiosity. And I found this in java/lang/Object.java.

There are three methods named wait:

  • public final native void wait(long timeout): This is the core of all wait methods, which has a native implementation.
  • public final void wait(): Just calls wait(0).
  • And then there is public final void wait(long timeout, int nanos).

The JavaDoc for the particular method tells me that,

This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The amount of real time, measured in nanoseconds, is given by:

1000000*timeout+nanos

But this is how the methods achieves "finer control over the amount of time to wait":

if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
    timeout++;
}

wait(timeout);

So this method basically does a crude rounding up of nanoseconds to milliseconds. Not to mention that anything below 500000ns/0.5ms will be ignored.

Is this piece of code bad/unnecessary code, or am I missing some unseen virtue of declaring this method, and it's no argument cousin as the way they are?

© Programmers or respective owner

Related posts about java