Skip to content

Instantly share code, notes, and snippets.

@zhuker
Created January 9, 2023 05:11
Show Gist options
  • Save zhuker/bce53547d3f97685afb7542550f08865 to your computer and use it in GitHub Desktop.
Save zhuker/bce53547d3f97685afb7542550f08865 to your computer and use it in GitHub Desktop.
@Test
fun sleepParkNanos() {
val nsec = 960 * 1000_000_000L / 48000
val looping = AtomicBoolean(true)
val histo = IntArray(10)
val t = Thread() {
val startTime = System.nanoTime()
var i = 0
while (looping.get()) {
val expected = i * nsec
val actual = System.nanoTime() - startTime
val dnsec = actual - expected
val dmsec = TimeUnit.NANOSECONDS.toMillis(dnsec).toInt()
histo[dmsec]++
// println(message)
LockSupport.parkNanos(nsec - dnsec)
i++
}
}
t.priority = MAX_PRIORITY
t.start()
Thread.sleep(20000)
looping.set(false)
println(histo.contentToString())
println("done")
}
@zhuker
Copy link
Author

zhuker commented Jan 9, 2023

on ubuntu 22 + openjdk 17 this produces:

[1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

meaning - it schedules execution after parkNanos at exactly the requested time at millisecond resolution

@zhuker
Copy link
Author

zhuker commented Jan 9, 2023

on macos 12 + temurin 17 this produces

[191, 224, 149, 320, 115, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

meaning it scheduled 191 times at 0 msec from expected time, 224 times 1 msec later, etc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment