当前位置 : 主页 > 编程语言 > java >

替代 System.currentTimeMillis() 的高性能时间戳生成器

来源:互联网 收集:自由互联 发布时间:2021-06-28
替代 System.currentTimeMillis() 的高性能时间戳生成器,高并发时 System.currentTimeMillis() 时很耗时的 public class SystemClock { private static final long PERIOD = 1; private volatile long now; private final ScheduledEx
替代 System.currentTimeMillis() 的高性能时间戳生成器,高并发时 System.currentTimeMillis() 时很耗时的
public class SystemClock {

    private static final long PERIOD = 1;

    private volatile long now;
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor((runnable) -> {
        Thread thread = new Thread(runnable, SystemClock.class.getSimpleName());
        thread.setDaemon(true);
        return thread;
    });
    private final Runnable updateClockRunner = () -> SystemClock.this.now = (System.currentTimeMillis());

    private SystemClock() {
        this.now = System.currentTimeMillis();
        startSchedule();
    }

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

    public static long now() {
        return instance().currentTimeMillis();
    }

    public static String nowDate() {
        return new Timestamp(instance().currentTimeMillis()).toString();
    }

    private void startSchedule() {
        scheduler.scheduleAtFixedRate(updateClockRunner, PERIOD, PERIOD, TimeUnit.MILLISECONDS);
    }

    private long currentTimeMillis() {
        return now;
    }

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

}
网友评论