不敢相信?System.currentTimeMillis()存在性能问题

System.currentTimeMillis()是极其经常使用的基础Java API,普遍地用来获取时间戳或测量代码执行时长等,在咱们的印象中应该快如闪电。但实际上在并发调用或者特别频繁调用它的状况下(好比一个业务繁忙的接口,或者吞吐量大的须要取得时间戳的流式程序),其性能表现会使人大跌眼镜。java

直接看代码linux

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");
 }
}
复制代码

执行结果以下图。缓存

不敢相信?System.currentTimeMillis()存在性能问题

可见,并发调用System.currentTimeMillis()一百次,耗费的时间是单线程调用一百次的250倍。若是单线程的调用频次增长(好比达到每毫秒数次的地步),也会观察到相似的状况。实际上在极端状况下,System.currentTimeMillis()的耗时甚至会比建立一个简单的对象实例还要多,看官能够自行将上面线程中的语句换成new HashMap<>之类的试试看。bash

为何会这样?并发

来到HotSpot源码的hotspot/src/os/linux/vm/os_linux.cpp文件中,有一个javaTimeMillis()方法,这就是System.currentTimeMillis()的native实现。高并发

不敢相信?System.currentTimeMillis()存在性能问题

挖源码就到此为止,由于已经有国外大佬深刻到了汇编的级别来探究,详情能够参见《The Slow currentTimeMillis()》这篇文章。简单来说就是:性能

  • 调用gettimeofday()须要从用户态切换到内核态;
  • gettimeofday()的表现受Linux系统的计时器(时钟源)影响,在HPET计时器下性能尤为差;
  • 系统只有一个全局时钟源,高并发或频繁访问会形成严重的争用。

HPET计时器性能较差的缘由是会将全部对时间戳的请求串行执行。TSC计时器性能较好,由于有专用的寄存器来保存时间戳。缺点是可能不稳定,由于它是纯硬件的计时器,频率可变(与处理器的CLK信号有关)。关于HPET和TSC的细节能够参见https://en.wikipedia.org/wiki/HighPrecisionEventTimer与https://en.wikipedia.org/wiki/TimeStamp_Counter。优化

另外,能够用如下的命令查看和修改时钟源。ui

~ 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
复制代码

如何解决这个问题?this

最多见的办法是用单个调度线程来按毫秒更新时间戳,至关于维护一个全局缓存。其余线程取时间戳时至关于从内存取,不会再形成时钟资源的争用,代价就是牺牲了一些精确度。具体代码以下。

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()的效率没有影响程序总体的效率时,就彻底没有必要作这种优化,这只是为极端状况准备的。

相关文章
相关标签/搜索