高并发调用System.currentTimeMillis的性能问题
为什么慢
文章http://pzemtsov.github.io/2017/07/23/the-slow-currenttimemillis.html有详细解释,主要有如下原因:
- JVM使用gettimeofday()而不是clock_gettime()
- gettimeofday() 如果使用HPET时间源,则速度非常慢。
但是,HPET现在不是唯一的时间源。最常见的时间源且许多系统使用的是TSC。在我们的项目中,服务器配置了HPET时间源,原因在于:此时间源与NTP客户端完美集成,可以平滑调整时间,而TSC不太稳定
解决方案
- 方案一:如果对时间精确度要求不高的话可以使用独立线程缓存时间戳。
- 方案二:使用Linux的clock_gettime()方法。
Java VM可以使用这个调用并且提供更快的速度currentTimeMillis()。
如果绝对必要,可以使用JNI自己实现它.
方案一:
package com.nyvi.support.util;
import java.sql.Timestamp;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* <p>
* 高并发场景下System.currentTimeMillis()的性能问题的优化
* </p>
* @author czk
*/
public class SystemClock {
private final long period;
private final AtomicLong now;
private SystemClock(long period) {
this.period = period;
this.now = new AtomicLong(System.currentTimeMillis());
scheduleClockUpdating();
}
private static SystemClock instance() {
return InstanceHolder.INSTANCE;
}
public static long now() {
return instance().currentTimeMillis();
}
public static String nowDate() {
return new Timestamp(instance().currentTimeMillis()).toString();
}
private void scheduleClockUpdating() {
ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "System Clock");
thread.setDaemon(true);
return thread;
}
});
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
now.set(System.currentTimeMillis());
}
}, period, period, TimeUnit.MILLISECONDS);
}
private long currentTimeMillis() {
return now.get();
}
private static class InstanceHolder {
public static final SystemClock INSTANCE = new SystemClock(1);
}
}
测试代码:
public class Test {
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (long i = 0; i < Integer.MAX_VALUE; i++) {
SystemClock.now();
}
long end = System.currentTimeMillis();
System.out.println("SystemClock Time:" + (end - start) + "毫秒");
long start2 = System.currentTimeMillis();
for (long i = 0; i < Integer.MAX_VALUE; i++) {
System.nanoTime();
}
long end2 = System.currentTimeMillis();
System.out.println("currentTimeMillis Time:" + (end2 - start2) + "毫秒");
}
}
控制台输出:
SystemClock Time:536毫秒 currentTimeMillis Time:41865毫秒
参考:
https://www.jianshu.com/p/3fbe607600a5