Last active
July 15, 2017 12:42
-
-
Save mabn/9587658d78d730917559cd61a274ea4f to your computer and use it in GitHub Desktop.
a clock with microsecond precision
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Slf4j | |
public class MicrosecondPrecisionClock implements Clock { | |
private static final long ONE_MINUTE_IN_NANOSECONDS = 60_000_000_000L; | |
private final long systemTimeOffsetNs; | |
private long lastWarningLoggedAt; | |
public MicrosecondPrecisionClock() { | |
systemTimeOffsetNs = System.currentTimeMillis() * 1_000_000 - System.nanoTime(); | |
} | |
@Override | |
public long currentTimeMicros() { | |
long currentNano = System.nanoTime(); | |
logInaccuracies(currentNano); | |
return (currentNano + systemTimeOffsetNs) / 1000; | |
} | |
private void logInaccuracies(long currentNano) { | |
long systemTimeNs = System.currentTimeMillis() * 1_000_000; | |
if (systemTimeNs > lastWarningLoggedAt + ONE_MINUTE_IN_NANOSECONDS) { | |
if (Math.abs(currentNano + systemTimeOffsetNs - systemTimeNs) > 250_000_000) { | |
log.warn("Detected significant difference between the clock based on nanoTime+offset = {} and currentTimeMillis={}", | |
currentNano + systemTimeOffsetNs, | |
systemTimeNs | |
); | |
lastWarningLoggedAt = systemTimeNs; | |
} | |
} | |
} | |
@Override | |
public long currentNanoTicks() { | |
return System.nanoTime(); | |
} | |
@Override | |
public boolean isMicrosAccurate() { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment