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

转载于:https://www.cnblogs.com/diyunpeng/archive/2012/03/14/2397041.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值