---
title: "高并发场景下 System.currentTimeMillis() 的性能问题"
author: "buru"
date: "2013-01-30T20:06:43Z"
tags: []
categories: ["开源软件"]
slug: "system-currenttimemillis"
draft: false
lastmod: "2013-01-30T20:07:54Z"
id: 1779991
url: "https://buru.iteye.com/blog/1779991"
---

System.currentTimeMillis()的调用比new一个普通对象要耗时的多（具体耗时高出多少我还没测试过，有人说是100倍左右），然而该方法又是一个常用方法，有时不得不使用，比如日志，在高并发情形下怎么做才好呢？
System.currentTimeMillis()之所以慢是因为去跟系统打了一次交道，什么快？内存！如果该方法从内存直接取数，那岂不是相当快，看代码：

```java

class MillisecondClock {
	private long rate = 0;// 频率
	private volatile long now = 0;// 当前时间

	private MillisecondClock(long rate) {
		this.rate = rate;
		this.now = System.currentTimeMillis();
		start();
	}

	private void start() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(rate);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				now = System.currentTimeMillis();
			}
		}).start();
	}

	public long now() {
		return now;
	}

	public static final MillisecondClock CLOCK = new MillisecondClock(10);
}

```

用的时候直接CLOCK.now()即可，你可以适当的进行变形，比如调整更新频率，开放构造函数，设置daemon线程，改为懒汉模式等等。
如下图是同时开启100个线程，每个线程并发请求一亿次的结果，可见耗时相差16倍左右（环境：JDK 1.7 win7 64位 4核 4G）。

![](http://dl.iteye.com/upload/attachment/0080/0844/761ce1cb-6ef5-35ee-b694-8c5f29130ec3.jpg)