读书人

JAVA怎么产生uuid

发布时间: 2012-11-03 10:57:44 作者: rapoo

JAVA如何产生uuid

直接通过java.util.randomUUID() 产生,源码如下:

  public static UUID randomUUID() {        SecureRandom ng = numberGenerator;        if (ng == null) {            numberGenerator = ng = new SecureRandom();        }        byte[] randomBytes = new byte[16];        ng.nextBytes(randomBytes);        randomBytes[6]  &= 0x0f;  /* clear version        */        randomBytes[6]  |= 0x40;  /* set to version 4     */        randomBytes[8]  &= 0x3f;  /* clear variant        */        randomBytes[8]  |= 0x80;  /* set to IETF variant  */        return new UUID(randomBytes);    }

?注意

 1.numberGenerator = ng = new SecureRandom(); 2.private static volatile SecureRandom numberGenerator = null;

?1.是连续赋值,引用相同

?2.volatile 标识某变量在内存中仅存在一份不存在copy,如果变量比较简单那么可以认为是线程同步的另外一种机制

?

读书人网 >编程

热点推荐