MilliSecondTimer.java
1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.dianping.cat.message.internal;
import java.util.concurrent.locks.LockSupport;
/**
* This timer provides milli-second precise system time.
*/
public class MilliSecondTimer {
private static long m_baseTime;
private static long m_startNanoTime;
private static boolean m_isWindows = false;
public static long currentTimeMillis() {
if (m_isWindows) {
if (m_baseTime == 0) {
initialize();
}
long elipsed = (long) ((System.nanoTime() - m_startNanoTime) / 1e6);
return m_baseTime + elipsed;
} else {
return System.currentTimeMillis();
}
}
public static void initialize() {
String os = System.getProperty("os.name");
if (os.startsWith("Windows")) {
m_isWindows = true;
m_baseTime = System.currentTimeMillis();
while (true) {
LockSupport.parkNanos(100000); // 0.1 ms
long millis = System.currentTimeMillis();
if (millis != m_baseTime) {
m_baseTime = millis;
m_startNanoTime = System.nanoTime();
break;
}
}
} else {
m_baseTime = System.currentTimeMillis();
m_startNanoTime = System.nanoTime();
}
}
}