1

The method Object#wait(long, long) in java.lang.Object states in it's documentation 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

This in itself makes sense, but the implementation does not reflect the documentation:

public final void wait(long timeout, int nanos) throws InterruptedException
{
    // ... Some range checks

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

    wait(timeout);
}

As you can see, instead of actually using the nanos parameter, it simply rounds it to milliseconds and adds it to the timeout parameter, which it then uses to call the less precise wait(long) method.


Why is the implementation of wait(long, long) so different from it's documentation? Is it an intrinsic method that is treated specially by the JVM?

Clashsoft
  • 11,553
  • 5
  • 40
  • 79

2 Answers2

2

It's possible that this is just the default implementation and the JVM intrinsifies it in a platform-specific manner when generating optimized code through its JIT compilers.

Similar things happen with - for example - Math.{min,max,abs} methods, they are implemented in java but get replaced by optimized assembly by the compilers.

As @Nitram mentioned, windows only provides millisecond OS-level thread scheduling/waiting. And even measuring (not even waiting) at nanosecond precision is fairly problematic under windows. I.e. the better implementations cannot be the default implementation because they are only available on some platforms.

the8472
  • 40,999
  • 5
  • 70
  • 122
0

As far as I know even the high precision timers in Windows give you a resolution down to a millisecond (MSDN page). And as Java internally has to use some timer implementation to handle the waiting operation, I guess that is the limiting factor.

Nitram
  • 6,486
  • 2
  • 21
  • 32
  • Then what is the point of having the `wait(long, long)` method anyways? To me, it would have made more sense to either remove it or, more reasonably, make it `native` and hide the actual implementation. – Clashsoft Apr 10 '15 at 09:26
  • 1
    I think timing this more precise can be done. I remember reading *somewhere* that with Linux you get resolutions below a millisecond, but I don't know how reliable timings at this level are on consumer computer. So either this `wait(long, long)` function is there for historical reasons because *someone* considered it a good idea, or there are special implementations of Java that have a differing implementation that provides a better resolution. – Nitram Apr 10 '15 at 09:31