本文出自taobao@boyan 《NIO trick and trap》
网络服务器通常需要频繁地获取系统时间:定时器、协议时间戳、缓存过期等等。
System.currentTimeMillis
>Linux调用gettimeofday,需要切换到内核态
>在我的机器上,1000万次调用需要12秒,平均一次1.3毫秒
>大部分应用并不需要特别高的精度
SystemTimer.currentTimeMillis
>独立线程定期更新时间缓存
>currentTimeMillis直接返回缓存值
>精度取决于定期间隔
>1000万次调用降低到59毫秒
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 出自 taobao.code
* 性能更高的系统时间类,适用于精度不是特别高的场景
* 另外:参考System.currentTimeMillis and System.nanoTime
* @author will_awoke
* @version 2014-5-26
* @see SystemTimer
* @since
*/
public class SystemTimer
{
private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
private static final long tickUnit = Long.parseLong(System.getProperty("notify.systimer.tick",
"50"));
private static volatile long time = System.currentTimeMillis();
private static class TimerTicker implements Runnable
{
@Override
public void run()
{
time = System.currentTimeMillis();
}
}
static
{
executor.scheduleAtFixedRate(new TimerTicker(), tickUnit, tickUnit, TimeUnit.MILLISECONDS);
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
executor.shutdown();
}
});
}
/**
* method that returns currentTimeMillis
* @return
* @see
*/
public static long currentTimeMillis()
{
return time;
}
}