UUID/签名/加解密工具并发场景下隐藏的性能瓶颈问题

时间:2025-03-30 14:27:58
public class UUIDUtil { private static final ThreadLocal<SecureRandom> RAND = ThreadLocal.withInitial(SecureRandom::new); public static UUID randomUUID() { SecureRandom ng = RAND.get(); byte[] randomBytes = new byte[16]; ng.nextBytes(randomBytes); // clear version randomBytes[6] &= 0x0f; // set to version 4 randomBytes[6] |= 0x40; // clear variant randomBytes[8] &= 0x3f; // set to IETF variant randomBytes[8] |= 0x80; long msb = 0; long lsb = 0; for (int i=0; i<8; i++) { msb = (msb << 8) | (randomBytes[i] & 0xff); } for (int i=8; i<16; i++) { lsb = (lsb << 8) | (randomBytes[i] & 0xff); } return new UUID(msb, lsb); } }