java currenttimemillis 效率_高并发场景下System.currentTimeMillis()的性能问题的优化

在高并发环境下,System.currentTimeMillis()的调用可能成为性能瓶颈。本文提出一种优化方案,通过创建SystemClock类并使用AtomicLong缓存时间戳,减少系统交互,提高效率。测试结果显示,优化后的SystemClock.now()方法相比System.currentTimeMillis()有显著的性能提升。
摘要由CSDN通过智能技术生成

前言

System.currentTimeMillis()的调用比new一个普通对象要耗时的多(具体耗时高出多少我也不知道,不过听说在100倍左右),然而该方法又是一个常用方法,有时不得不使用,比如生成wokerId、打印日志什么的,在高并发情形下肯定存在性能问题的,但怎么做才好呢? System.currentTimeMillis()之所以慢是因为去跟系统打了一次交道。那什么快?内存!如果该方法从内存直接取数,那不就美滋滋了。

代码实现

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;

/**

*

* 高并发场景下System.currentTimeMillis()的性能问题的优化

*

* @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);

}

}

用的时候直接调用SystemClock.now();就ok了。

测试

写了一个简单的测试代码:

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.currentTimeMillis();

}

long end2 = System.currentTimeMillis();

System.out.println("currentTimeMillis Time:" + (end2 - start2) + "毫秒");

}

输出结果是:

SystemClock Time:1787毫秒

currentTimeMillis Time:33851毫秒

看着结果效率提升还是挺明显的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值