currenttimemillis
前言
在高并发场景下system.currenttimemillis()并发问题严重,甚至比创建一个普通对象要耗时的多;在系统中有时候不可避免要打印一些时间戳,但怎么做才更好呢。
代码实现
iimport java.util.concurrent.Executors;
import java.util.concurrent.scheduledexecutorservice;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* 高并发场景下System.currentTimeMillis()的性能问题的优化
* 时间戳打印建议使用
*/
public class SystemClock {
private static final String THREAD_NAME = "system.clock";
private static final SystemClock MILLIS_CLOCK = new SystemClock(1);
private final long precision;
private final AtomicLong now;
private SystemClock(long precision) {
this.precision = precision;
now = new AtomicLong(System.currentTimeMillis());
scheduleClockUpdating();
}
public static SystemClock millisClock() {
return MILLIS_CLOCK;
}
private void scheduleClockUpdating() {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
Thread thread = new Thread(runnable, THREAD_NAME);
thread.setDaemon(true);
return thread;
});
scheduler.scheduleatfixedrate(() ->
now.set(System.currentTimeMillis()), precision, precision, TimeUnit.MILLISECONDS);
}
public long now() {
return now.get();
}
}
调用示例
Long start = SystemClock.millisClock().now()
测试对比
public static void main(String[] args) {
int times=integer.MAX_VALUE;
long start = System.currentTimeMillis();
for (long i = 0; i < times; i++) {
SystemClock.millisClock().now();
}
long end = System.currentTimeMillis();
System.out.println("SystemClock Time:" + (end - start) + "毫秒");
long start2 = System.currentTimeMillis();
for (long i = 0; i < times; i++) {
System.currentTimeMillis();
}
long end2 = System.currentTimeMillis();
System.out.println("SystemCurrentTimeMillis Time:" + (end2 - start2) + "毫秒");
}
输出结果是:
SystemClock Time:2741毫秒
SystemCurrentTimeMillis Time:14072毫秒
五倍的效率
细节决定成败,敬畏每一行代码,代码优化永无止境!
相关阅读
通过system.currentTimeMillis() 获得当前的时间
System一个很牛掰的类 ,位于java.lang包下,有很多可以获取到系统底层的东西,现分享一二:System类本意就代表系统,系统级的很多属性和控
谈谈获取系统时间,以及和服务端交互时的时间校验 背景 最近玩旅行青蛙,偶然发现在没有网络情况下,还是可以正常的收三叶草以及