import java.util.Date;
public class MySnowFlake {
private long lastTimestamp = -1L;
private int sequence;
private final int sequenceMask=999;
public MySnowFlake(Integer sequence){
if (sequence<0||sequence>sequenceMask){
throw new IllegalArgumentException(
"sequence can't be greater than 999 or lesser than 0"
);
}
this.sequence=sequence;
}
public synchronized String nextId() {
String result="";
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
System.err.printf(
"clock is moving backwards. Rejecting requests until %d.", lastTimestamp);
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
lastTimestamp - timestamp));
}
if (lastTimestamp == timestam
java 雪花算法改造(带日期格式)毫秒级
雪花算法实现:生成唯一ID的SnowFlake序列
最新推荐文章于 2023-12-20 19:12:46 发布
本文介绍了一个使用Java实现的SnowFlake算法,用于生成全局唯一的ID,包括序列生成、时间戳处理和序列溢出处理。通过实例展示了ID的生成过程。

最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



