java生成指定长度uuid_java – 固定长度的唯一ID创建

在分布式系统中,通过AtomicLong结合System.currentTimeMillis()生成当前时间毫秒值,并使用shuffleBits方法进行位操作打乱,以创建唯一的非连续ID。虽然不及UUID安全,但速度较快。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果这当然是一个分布式系统,那么这将不起作用,但如下所示.

private AtomicLong uniqueId = new AtomicLong(0);

...

// get a unique current-time-millis value

long now;

long prev;

do {

prev = uniqueId.get();

now = System.currentTimeMillis();

// make sure now is moving ahead and unique

if (now <= prev) {

now = prev + 1;

}

// loop if someone else has updated the id

} while (!uniqueId.compareAndSet(prev, now));

// shuffle it

long result = shuffleBits(now);

System.out.println("Result is " + Long.toHexString(result));

public static long shuffleBits(long val) {

long result = 0;

result |= (val & 0xFF00000000000000L) >> 56;

result |= (val & 0x00FF000000000000L) >> 40;

result |= (val & 0x0000FF0000000000L) >> 24;

result |= (val & 0x000000FF00000000L) >> 8;

result |= (val & 0x00000000FF000000L) << 8;

result |= (val & 0x0000000000FF0000L) << 24;

result |= (val & 0x000000000000FF00L) << 40;

result |= (val & 0x00000000000000FFL) << 56;

return result;

}

可以改进位混洗以在每次迭代中产生更多值的变化.您提到您不希望数字是连续的,但您没有指定完全随机的要求.

当然不如UUID好,但比数据库操作快.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值