package org.apache.logging.log4j.core.util;

import java.util.concurrent.locks.LockSupport;

public final class CachedClock implements Clock {
   private static final int UPDATE_THRESHOLD = 1023;
   private static final CachedClock instance = new CachedClock();
   private volatile long millis = System.currentTimeMillis();
   private volatile short count = 0;

   private CachedClock() {
      Thread updater = new Thread(new Runnable() {
         public void run() {
            while(true) {
               long time = System.currentTimeMillis();
               CachedClock.this.millis = time;
               LockSupport.parkNanos(1000000L);
            }
         }
      }, "Clock Updater Thread");
      updater.setDaemon(true);
      updater.start();
   }

   public static CachedClock instance() {
      return instance;
   }

   public long currentTimeMillis() {
      if ((++this.count & 1023) == 1023) {
         this.millis = System.currentTimeMillis();
      }

      return this.millis;
   }
}
