java currenttimemillis 效率_「currenttimemillis」高并发下System.currentTimeMillis()并发问题以及优化对比 - seo实验室...

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一个很牛掰的类 ,位于java.lang包下,有很多可以获取到系统底层的东西,现分享一二:System类本意就代表系统,系统级的很多属性和控

谈谈获取系统时间,以及和服务端交互时的时间校验

背景

最近玩旅行青蛙,偶然发现在没有网络情况下,还是可以正常的收三叶草以及

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值