当前位置 : 主页 > 编程语言 > c++ >

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

来源:互联网 收集:自由互联 发布时间:2021-07-03
MybatisPlus 自带SystemClock优化System.currentTimeMillis()性能 public class SystemClock { //频率 private final long period; private final AtomicLong now; private SystemClock(long period) { this.period = period; this.now = new AtomicL
MybatisPlus 自带SystemClock优化System.currentTimeMillis()性能
public class SystemClock {
    //频率
    private final long period;
    private final AtomicLong now;

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

    private static SystemClock instance() {
        return SystemClock.InstanceHolder.INSTANCE;
    }

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

    public static String nowDate() {
        return (new Timestamp(instance().currentTimeMillis())).toString();
    }

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

    private long currentTimeMillis() {
        return this.now.get();
    }

    private static class InstanceHolder {
        public static final SystemClock INSTANCE = new SystemClock(1L, null);

        private InstanceHolder() {
        }
    }
}
网友评论