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

JerryXia 发表于 , 阅读 (4,851)

System.currentTimeMillis()的调用比new一个普通对象要耗时的多(具体耗时高出多少我还没测试过,有人说是100倍左右)

System.currentTimeMillis()之所以慢是因为去跟系统打了一次交道

后台定时更新时钟,JVM退出时,线程自动回收,得到的数据

10亿:43410,206,210.72815533980582%
1亿:4699,29,162.0344827586207%
1000万:480,12,40.0%
100万:50,10,5.0%

参考代码如下:

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

public class SystemClock {
    private final long period;
    private volatile long now;

    private static final SystemClock instance = new SystemClock(1);

    private SystemClock(long period) {
        this.period = period;
        // this.now = new AtomicLong(System.currentTimeMillis());
        this.now = System.currentTimeMillis();
        scheduleClockUpdating();
    }

    public static long now() {
        return instance.currentTimeMillis();
    }

    public static Date nowDate() {
        return new Date(instance.currentTimeMillis());
    }

    private void scheduleClockUpdating() {
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            public Thread newThread(Runnable runnable) {
                Thread thread = new Thread(runnable, "SystemClock");
                thread.setDaemon(true);
                return thread;
            }
        });
        scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                now = System.currentTimeMillis();
            }
        }, period, period, TimeUnit.MILLISECONDS);
    }

    private long currentTimeMillis() {
        return now;
    }
}
暂无评论
  1. Demo

    你好,我是一名QAD使用者,这个软件超过20分钟不操作就会自动退出。所以,我使用你做的这个防休眠小脚本,可是还是会出现QAD自动退出的情况,请问是怎么回事?

    1. JerryXia

      我模拟的是win10系统在操作,而不是指定的软件,你需要的是按键精灵或AutoHotkey之类的工具。

添加新评论