高并发情况下System.currentTimeMillis()的优化

  认为System.currentTimeMillis()慢,是因为每次调用都会去跟系统打一次交道,在高并发情况下,大量并发的系统调用容易会影响性能(对它的调用甚至比new一个普通对象都要耗时,毕竟new产生的对象只是在Java内存中的堆中)。
  通过在内存中缓存最新时间,并使用一个守护线程每毫秒更新一次即可很大程序的提高性能。优化后只会有一个线程在频繁的执行系统调用,而且是分布在不同时间点上。代码如下

package com.tvl.job.core.sequence;

import java.sql.Timestamp;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @description
 * @author st.z
 */
public class SystemClock {

	private final int period;

	private final AtomicLong now;

	private static final SystemClock INSTANCE = new SystemClock(1);

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

	private void scheduleClockUpdating() {
		ScheduledExecutorService scheduleService = Executors.newSingleThreadScheduledExecutor((r) -> {
			Thread thread = new Thread(r);
			thread.setDaemon(true);
			return thread;
		});
		scheduleService.scheduleAtFixedRate(() -> {
			now.set(System.currentTimeMillis());
		}, 0, period, TimeUnit.MILLISECONDS);
	}

	private long get() {
		return now.get();
	}

	public static long now() {
		return INSTANCE.get();
	}

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

}

 

你可能感兴趣的:(高并发情况下System.currentTimeMillis()的优化)