问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/29557663/java-object-waitlong-long-implementation-different-from-documentation