java产生随机uuid的性能
在java中产生uuid的方式是使用java.util.UUID。 UUID.randomUUID().toString(); 我在测试redis性能时,使用uuid产生测试数据,发现多线程测试redis的rpush接口的时候,性能老是上不去。 查看cpu利用率也不高,网卡流量也不大。就是tps上不去。但是如果用两台client去测,又可以达到更高的tps。 后来直接用jstack查看了下堆栈,发现大多数线程停留在: java.lang.Thread.State: BLOCKED (on object monitor) at java.security.SecureRandom.nextBytes(Unknown Source) - waiting to lock <0x00000005ffe1c548> (a java.security.SecureRandom) at java.util.UUID.randomUUID(Unknown Source) 原来uuid的生成遇到了性能瓶颈。于是我单独测试了下生成随机uuid的性能,发现无论是1个线程还是32个线程还是300个线程,它的tps只能到10万级别。 甚至是线程数越大,tps越低。tps在每个机器上都不一样,有的机器上测试tps只有5万。我们就以一台双核4G内存的虚拟机为例: tps在 140000+ 我们看randomUUID方法的javadoc的描述是: The UUID is generated using a cryptographically strong pseudo random number generator 也就是说uuid使用了一个强随机数,也也保证了uuid的不重复性。 public static UUID randomUUID() { SecureRandom ng=numberGenerator; if(ng == null) numberGenerator=ng=new SecureRandom(); byte[] randomBytes=new byte[16]; ng.nextBytes(randomBytes); return new UUID(randomBytes); } 再看SecureRandom的javadoc Note: Depending on the implementation, the generateSeed and nextBytes methods may block as entropy is being gathered, for example, if they need to read from /dev/random on various unix-like operating systems. ...