RFR: 8305092: Improve Thread.sleep(millis, nanos) for sub-millisecond granularity [v4]

Aleksey Shipilev shade at openjdk.org
Wed Apr 19 09:56:44 UTC 2023


> Java API has the `Thread.sleep(millis, nanos)` method exposed to users. The documentation for that method clearly says the precision and accuracy are dependent on the underlying system behavior. However, it always rounds up `nanos` to 1ms when doing the actual sleep. This means users cannot do the micro-second precision sleeps, even when the underlying platform allows it. Sub-millisecond sleeps are useful to build interesting primitives, like the rate limiters that run with >1000 RPS.
> 
> When faced with this, some users reach for more awkward APIs like `java.util.concurrent.locks.LockSupport.parkNanos`. The use of that API for sleeps is not in line with its intent, and while it "seems to work", it might have interesting interactions with other uses of `LockSupport`. Additionally, these "sleeps" are no longer visible to monitoring tools as "normal sleeps", e.g. as `Thread.sleep` events. Therefore, it would be prudent to improve current `Thread.sleep(millis, nanos)` for sub-millisecond granularity. 
> 
> Fortunately, the underlying code is almost ready for this, at least on POSIX side. I skipped Windows paths, because its timers are still no good. Note that on both Linux and MacOS timers oversleep by about 50us. I have a few ideas how to improve the accuracy for them, which would be a topic for a separate PR.
> 
> Additional testing:
>   - [x] New regression test
>   - [x] New benchmark
>   - [x] Linux x86_64 `tier1`
>   - [x] Linux AArch64 `tier1`

Aleksey Shipilev has updated the pull request incrementally with six additional commits since the last revision:

 - Adjust assert
 - Replace (park|sleep)_millis back with just (park|sleep)
 - More review touchups
 - Revert some Thread refactorings
 - Add a few missing sleep_millis renames
 - Adjust the test a bit

-------------

Changes:
  - all: https://git.openjdk.org/jdk/pull/13225/files
  - new: https://git.openjdk.org/jdk/pull/13225/files/33fa34f1..f78aef54

Webrevs:
 - full: https://webrevs.openjdk.org/?repo=jdk&pr=13225&range=03
 - incr: https://webrevs.openjdk.org/?repo=jdk&pr=13225&range=02-03

  Stats: 57 lines in 16 files changed: 23 ins; 2 del; 32 mod
  Patch: https://git.openjdk.org/jdk/pull/13225.diff
  Fetch: git fetch https://git.openjdk.org/jdk.git pull/13225/head:pull/13225

PR: https://git.openjdk.org/jdk/pull/13225


More information about the core-libs-dev mailing list