On Wed, 29 Mar 2023 16:48:41 GMT, David M. Lloyd <[email protected]> wrote:
> Are there specific factors which would make it unreasonable to implement
> `sleep` in terms of `parkNanos`?
After reading the Javadoc for `LockSupport`, I don't believe implementing
`Thread.sleep` with `LockSupport.parkNanos` is a proper thing to do.
`LockSupport` implicitly deals with permits, acting like a single-permit
semaphore. So the behavior for `parkNanos` when there is a prior
`LockSupport.unpark` (which adds the permit) is to consume the permit and
return immediately.
In other words:
% cat LockSupportIsNotSleep.java
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.TimeUnit;
public class LockSupportIsNotSleep {
public static void main(String... args) {
LockSupport.unpark(Thread.currentThread());
long time1 = System.nanoTime();
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1000));
long time2 = System.nanoTime();
System.out.println("Slept for " + (time2 - time1) + " ns");
}
}
% java LockSupportIsNotSleep.java
Slept for 6583 ns
-------------
PR Comment: https://git.openjdk.org/jdk/pull/13225#issuecomment-1489000794