做者:LittleMagic
连接:https://www.jianshu.com/p/d2039190b1cbhtml
System.currentTimeMillis()是极其经常使用的基础Java API,普遍地用来获取时间戳或测量代码执行时长等,在咱们的印象中应该快如闪电。java
但实际上在并发调用或者特别频繁调用它的状况下(好比一个业务繁忙的接口,或者吞吐量大的须要取得时间戳的流式程序),其性能表现会使人大跌眼镜。linux
直接看下面的Demo。git
public class CurrentTimeMillisPerfDemo { private static final int COUNT = 100; public static void main(String[] args) throws Exception { long beginTime = System.nanoTime(); for (int i = 0; i < COUNT; i++) { System.currentTimeMillis(); } long elapsedTime = System.nanoTime() - beginTime; System.out.println("100 System.currentTimeMillis() serial calls: " + elapsedTime + " ns"); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch endLatch = new CountDownLatch(COUNT); for (int i = 0; i < COUNT; i++) { new Thread(() -> { try { startLatch.await(); System.currentTimeMillis(); } catch (InterruptedException e) { e.printStackTrace(); } finally { endLatch.countDown(); } }).start(); } beginTime = System.nanoTime(); startLatch.countDown(); endLatch.await(); elapsedTime = System.nanoTime() - beginTime; System.out.println("100 System.currentTimeMillis() parallel calls: " + elapsedTime + " ns"); } }
执行结果以下图。github
可见,并发调用System.currentTimeMillis()一百次,耗费的时间是单线程调用一百次的250倍。spring
若是单线程的调用频次增长(好比达到每毫秒数次的地步),也会观察到相似的状况。缓存
实际上在极端状况下,System.currentTimeMillis()的耗时甚至会比建立一个简单的对象实例还要多,看官能够自行将上面线程中的语句换成new HashMap<>之类的试试看。bash
为何会这样呢?并发
来到HotSpot源码的hotspot/src/os/linux/vm/os_linux.cpp文件中,有一个javaTimeMillis()方法,这就是System.currentTimeMillis()的native实现。intellij-idea
jlong os::javaTimeMillis() { timeval time; int status = gettimeofday(&time, NULL); assert(status != -1, "linux error"); return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); }
挖源码就到此为止,由于已经有国外大佬深刻到了汇编的级别来探究,详情能够参见 The Slow currentTimeMillis() 这篇文章,我就不班门弄斧了。
http://pzemtsov.github.io/2017/07/23/the-slow-currenttimemillis.html
简单来说就是:
HPET计时器性能较差的缘由是会将全部对时间戳的请求串行执行。TSC计时器性能较好,由于有专用的寄存器来保存时间戳。缺点是可能不稳定,由于它是纯硬件的计时器,频率可变(与处理器的CLK信号有关)。关于HPET和TSC的细节能够参见:
https://en.wikipedia.org/wiki/High_Precision_Event_Timer
https://en.wikipedia.org/wiki/Time_Stamp_Counter
另外,能够用如下的命令查看和修改时钟源。
~ cat /sys/devices/system/clocksource/clocksource0/available_clocksource tsc hpet acpi_pm ~ cat /sys/devices/system/clocksource/clocksource0/current_clocksource tsc ~ echo 'hpet' > /sys/devices/system/clocksource/clocksource0/current_clocksource
如何解决这个问题?最多见的办法是用单个调度线程来按毫秒更新时间戳,至关于维护一个全局缓存。其余线程取时间戳时至关于从内存取,不会再形成时钟资源的争用,代价就是牺牲了一些精确度。具体代码以下。
public class CurrentTimeMillisClock { private volatile long now; private CurrentTimeMillisClock() { this.now = System.currentTimeMillis(); scheduleTick(); } private void scheduleTick() { new ScheduledThreadPoolExecutor(1, runnable -> { Thread thread = new Thread(runnable, "current-time-millis"); thread.setDaemon(true); return thread; }).scheduleAtFixedRate(() -> { now = System.currentTimeMillis(); }, 1, 1, TimeUnit.MILLISECONDS); } public long now() { return now; } public static CurrentTimeMillisClock getInstance() { return SingletonHolder.INSTANCE; } private static class SingletonHolder { private static final CurrentTimeMillisClock INSTANCE = new CurrentTimeMillisClock(); } }
使用的时候,直接CurrentTimeMillisClock.getInstance().now()
就能够了。不过,在System.currentTimeMillis()的效率没有影响程序总体的效率时,就没必要忙着作优化,这只是为极端状况准备的。
近期热文推荐:
1.Java 15 正式发布, 14 个新特性,刷新你的认知!!
2.终于靠开源项目弄到 IntelliJ IDEA 激活码了,真香!
3.我用 Java 8 写了一段逻辑,同事直呼看不懂,你试试看。。
以为不错,别忘了随手点赞+转发哦!