public enum IdUtil {
DATE_TIME_ID {
public long generateId() {
return Long.parseLong(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")
.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(super.generateId()), ZoneId.systemDefault())));
}
},
TIMESTAMP_ID {
public long generateId() {
return super.generateId();
}
},
SHIFT_ID {
public long generateId() {
return super.generateId() << 10;
}
};
private long lastTimestamp = -1L;
private Lock lock = new ReentrantLock();
private long nowTimestamp;
public long generateId() {
lock.lock();
nowTimestamp = 0;
try {
nowTimestamp = Instant.now().toEpochMilli();
if (lastTimestamp == nowTimestamp) {
lastTimestamp = waitNextMilli();
} else if (lastTimestamp > nowTimestamp) {
throw new RuntimeException("time error when generated the id.");
} else {
lastTimestamp = nowTimestamp;
}
} finally {
lock.unlock();
}
if (nowTimestamp == 0) {
throw new RuntimeException("unknown error when generated the id.");
}
return nowTimestamp;
}
private long waitNextMilli() {
do {
nowTimestamp = Instant.now().toEpochMilli();
} while (nowTimestamp == lastTimestamp);
return nowTimestamp;
}
}