天天看点

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

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

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好,但比数据库操作快.