高并发场景下System.currentTimeMillis()的性能问题优化

你也许用过System.currentTimeMillis(),但是你可能不知道它在高并发场景下对性能的影响。之前的测试数据具体多少我忘记了,但是我大概记得System.currentTimeMillis()的调用比new一个普通对象要耗时的多(具体耗时高出多少我还没测试过,有人说是100倍左右)。因此在高并发下,在高频率使用System.currentTimeMillis()的情况下,我们很有必要对System.currentTimeMillis()进行一次优化。

System.currentTimeMillis()之所以慢是因为去跟系统打了一次交道。具体需要你看过源码才知道。

本优化实现后台定时更新时钟,http://www.anbomei.com/f05d/70458af4e518.htmlJVM退出时,线程自动回收。

下面是相关优化的具体代码:

public class SystemClock {
	private final long period;
	private final AtomicLong now;
	// 业余草:www.xttblog.com
	private SystemClock(long phttp://www.anbomei.com/9d97/0fa7cf8f5d4e.htmleriod) {
		this.period = period;
		this.now = new AtomicLhttp://www.anbomei.com/e048/32e7a1bab4be.htmlong(System.currentTimeMillis());
		scheduleClockUpdating();
	}
	private shttp://www.anbomei.com/d4cd/a908d2c61b60.htmltatic class InstanceHolder {
		public static final SystemClock INShttp://www.anbomei.com/7c97/ea3f0f0a5a57.htmlTANCE = new SystemClock(1);
	}
	private static SystemClock instance()http://www.anbomei.com/e573/5889520866dd.html {
		return InstanceHolder.INSTANCE;
	}
	private void scheduleClockUpdating() {
		ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
			public Thread newThread(Runnable runnable) {
				Thread thread = new Thread(runnable, "System Clock");
				thread.setDaemonhttp://www.anbomei.com/c305/993ab39883a3.html(true);
				return thread;
			}
		});
		scheduler.schedulehttp://www.anbomei.com/6c48/d53337fda7f6.htmlAtFixedRate(new Runnable()http://www.anbomei.com/c6e9/47b17a0bdf7e.html {
			public void run() {
				now.set(System.currentTimeMillis());
			}
		}, period, period, TimeUnit.MILLISECONDS);
	}
	prhttp://www.anbomei.com/9d3b/97c235529825.htmlivate long currentTimeMillis() {
		return now.get();
	}
	public static long now() {
		return instance().currentTimeMillis();
	}
	public static String nowDate() {
		return new Timestamp(instance().currentTimeMillis()).toString();
	}
}

下面是大量测试后得出的结果:

10亿:43410,206,210.72815533980582%
1亿:4699,29,162.0344827586207%
1000万:480,12,40.0%
100万:50,10,5.0%

以上上个仅供参考,具体和你的硬件配置等有关。

业余草公众号

最后,欢迎关注我的个人微信公众号:业余草(yyucao)!