併發下獲取當前時間類優化

高併發場景下System.currentTimeMillis()的性能問題的優化
System.currentTImeMillis()的調用比new一個普通對象要耗時的多(具體耗時高出多少我還沒有測試過,有人說是100倍左右)
System,currentTimeMillis()之所以慢是因爲去跟系統打了一次交道
後臺定時更新時鐘,JVM退出,線程自動回收

package com.company;

import java.sql.Timestamp;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 高併發場景下System.currentTimeMillis()的性能問題的優化
 * System.currentTimeMillis()的調用比new一個普通對象要耗時得多,具體耗時高出多少我還沒有測試過,有人說是100倍左右
 * System.currentTimeMillis()之所以慢是因爲去梗系統打了一次交道
 * 後臺定時更新時鐘,JVM退出時,線程自動回收
 */

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

    ExecutorService executor = Executors.newSingleThreadExecutor();

    private static final long periodTime = 1;

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

   private static class InstanceHolder{
        public static final SystemClock INSTANCE = new SystemClock(periodTime);
   }

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

   private void scheduleClockUpdating(){
       ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
           @Override
           public Thread newThread(Runnable runnable) {
               Thread thread = new Thread(runnable, "System Clock");
               thread.setDaemon(true);
               return thread;
           }
       });
       scheduler.scheduleAtFixedRate(new Runnable() {
           @Override
           public void run() {
               now.set(System.currentTimeMillis());
           }
       },period,period, TimeUnit.MILLISECONDS);
   }
   private long currentTimeMillis(){
        return now.get();
   }
   public static long now(){
        return instance().currentTimeMillis();
   }
   public static String nowDate(){
        return new Timestamp(instance().currentTimeMillis()).toString();
   }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章