美文网首页
2019-11-21 高并发下System.currentTim

2019-11-21 高并发下System.currentTim

作者: Albert陈凯 | 来源:发表于2019-11-21 12:04 被阅读0次

    前言

    在高并发场景下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毫秒
    五倍的效率

    细节决定成败,敬畏每一行代码,代码优化永无止境!

    转载于:https://www.cnblogs.com/mengq0815/p/10596067.html

    相关文章

      网友评论

          本文标题:2019-11-21 高并发下System.currentTim

          本文链接:https://www.haomeiwen.com/subject/ruozictx.html