You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提升Java中System.currentTimeMillis()的并发调用性能?

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

System.currentTimeMillis()是Java中获取当前毫秒时间戳的常用本地方法,串行调用时基本无性能问题,但高并发持续调用时会出现明显性能瓶颈——根源在于它依赖操作系统的clock_source,每次调用都会触发系统调用,并发场景下还会产生锁竞争。针对你的耗时测量场景,可采用以下优化方案:

1. 用System.nanoTime()替代(优先推荐)

System.nanoTime()是专门用于测量时间间隔的API,它不依赖系统墙钟,调用时的系统开销远低于System.currentTimeMillis(),并发场景下几乎无锁竞争问题,完全适配耗时测量需求。

修改你的示例代码如下:

int parallism = 32;

for(int i=0;i< parallism ;i++){
    new Thread(() -> {
        for(;;){

            // 改用nanoTime测量耗时
            long begin = System.nanoTime();
            
            // 业务逻辑:此处为空块,理论耗时为0
            
            // 转换为毫秒(若无需纳秒精度可省略转换)
            long elapsed = (System.nanoTime() - begin) / 1_000_000;
            if(elapsed >= 5){
                System.err.println("Elapsed: "+elapsed+" ms.");
            }
        }
    }).start();
}

Thread.sleep(Integer.MAX_VALUE); // 防止进程退出

2. 若必须使用当前毫秒时间戳的优化方案

如果你的场景并非仅测量耗时,而是需要获取当前时间戳,可采用单线程定时更新全局缓存的方式:用后台线程定期更新全局时间戳变量,其他线程直接读取缓存值,避免频繁调用System.currentTimeMillis()。该方案存在微小时间误差,适合对时间精度要求不高的场景。

简化版示例代码:

public class CachedClock {
    private static volatile long currentTimeMillis;

    static {
        currentTimeMillis = System.currentTimeMillis();
        // 后台线程每隔1毫秒更新一次(可根据精度需求调整间隔)
        new Thread(() -> {
            while (true) {
                currentTimeMillis = System.currentTimeMillis();
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }, "CachedClock-Updater").start();
    }

    public static long currentTimeMillis() {
        return currentTimeMillis;
    }
}

使用时直接调用CachedClock.currentTimeMillis()即可,并发场景下性能会大幅提升。

内容的提问来源于stack exchange,提问作者sunxien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 04:20:27