High Resolution Timer in Java 5
High Resolution Timer in Java 5
Last week I needed to generate (somewhat) high-frequency recurring events in Java for my thesis work. Nothing like real time, just call a method from 10 to 1000 times per second, but I want to able to tune it so it can run at a precise frequency in this interval. Should be easy, right? In theory it is: discover the period of recurrence, do the action, sleep the remaining time until the next occurrence. For example: if I want to generate 500 events per second and my action takes 200µs, then my period is 2ms and I must sleep 1800µs between executions.
So, I need microsecond precision for the sleep. It is widely known that this is impossible in Java 1.4 without some native code. Fortunately, in Java 5 it's pretty easy to get nanosecond precision and this blog entry is very, very informative. Briefly, if you want to measure a time delta with nanosecond precision use System.nanoTime(), if you want to schedule a (possibly recurring) event with the same precision use the ScheduledThreadPoolExecutor class. I ended up using the former for my code.
But now, the weird part. Along with System.nanoTime(), Java 5 introduced the Object.wait(millis, nanos) and Thread.sleep(millis, nanos) methods for high resolution sleeps. Take a look at the source code for the implementation of these methods here (gotta love free software!). See. These methods just round up or down the millisecond argument using the nanosecond argument and call the millisecond only version of the methods. It took me some time and a bit of frustration to notice this. Annoying. You might be wondering: how the heck is ScheduledThreadPoolExecutor implemented then? The answer is another sleep method introduced in Java 5: LockSupport.parkNanos. This one actually works, as it uses a different native implementation.
http://stackoverflow.com/questions/912623/how-can-i-speed-up-java-datagramsocket-performance
http://www.sagui.org/~gustavo/blog/code
http://stackoverflow.com/questions/824110/accurate-sleep-for-java-on-windows
http://stackoverflow.com/questions/9143719/java-alternative-to-thread-sleep
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术