1. 程式人生 > >高併發下System.currentTimeMillis()併發問題以及優化對比

高併發下System.currentTimeMillis()併發問題以及優化對比

前言

在高併發場景下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毫秒 五倍的效率

細節決定成敗,敬畏每一行程式碼,程式碼優化永無止境!