Use nanoTime replace currentTimemill to avoid clock backwards (#6740)

This commit is contained in:
Wenjun Ruan 2021-11-08 22:26:17 +08:00 committed by GitHub
parent b6824b4741
commit 0f94577d26
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 4 additions and 1 deletions

View File

@ -35,6 +35,9 @@ public class SnowFlakeUtils {
private long sequence = 0L;
private long lastTimestamp = -1L;
private static final long SYSTEM_TIMESTAMP = System.currentTimeMillis();
private static final long SYSTEM_NANOTIME = System.nanoTime();
private SnowFlakeUtils() throws SnowFlakeException {
try {
this.machineId = Math.abs(Objects.hash(InetAddress.getLocalHost().getHostName())) % 32;
@ -80,7 +83,7 @@ public class SnowFlakeUtils {
}
private long nowTimestamp() {
return System.currentTimeMillis();
return SYSTEM_TIMESTAMP + (System.nanoTime() - SYSTEM_NANOTIME) / 1000000;
}
public static class SnowFlakeException extends Exception {