2019-11-21 高并发下System.currentTimeMillis()并发问题以及优化对比

2019-11-21 21:49:44 浏览数 (1)

前言

在高并发场景下System.currentTimeMillis()并发问题严重,甚至比创建一个普通对象要耗时的多;在系统中有时候不可避免要打印一些时间戳,但怎么做才更好呢。

代码实现

代码语言:javascript复制
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()

测试对比

代码语言:javascript复制
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

0 人点赞