SecureRandom在java各種組件中使用廣泛,可以可靠的產生隨機數。但在大量產生隨機數的場景下,性能會較低。這時可以使用"-Djava.security.egd=file:/dev/./urandom"加快隨機數產生過程。
以產生uuid的時候使用nextBytes產生隨機數爲入口,我們看一下SecureRandom的代碼邏輯。
public static UUID randomUUID() { SecureRandom ng =Holder.numberGenerator; byte[] randomBytes = newbyte[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 newUUID(randomBytes); }
使用了SecureRandom.next*的方法。
在使用SecureRandom產生下一個隨機數的時候調用nextLong或者nextBytes,最終會調用SecureRandom的nextBytes。
public long nextLong() { // it's okay that the bottom wordremains signed. return ((long)(next(32)) << 32)+ next(32); } final protected int next(int numBits) { int numBytes = (numBits+7)/8; byte b[] = new byte[numBytes]; int next = 0; nextBytes(b); for (int i = 0; i < numBytes; i++) next = (next << 8)+ (b[i] & 0xFF); return next >>> (numBytes*8 -numBits); }
而nextBytes是一個同步的方法,在多線程使用時,可能會產生性能瓶頸。
synchronized public void nextBytes(byte[] bytes) { secureRandomSpi.engineNextBytes(bytes); }
secureRandomSpi被初始化爲sun.security.provider.SecureRandom
secureRandomSpi是SecureRandom.NativePRNG的一個實例。
使用jvm參數-Djava.security.debug=all ,可以打印securityprovider列表,從中可以看出,SecureRandom.NativePRNG由sun.security.provider.NativePRNG提供服務。
Provider: Set SUN provider property[SecureRandom.NativePRNG/sun.security.provider.NativePRNG]
分析openjdk的源碼,NativePRNG.engineNextBytes調用了NativePRNG.RandomIO.ensureBufferValid,而ensureBufferValid直接從urandom讀取數據:
private void ensureBufferValid() throws IOException { ... readFully(urandomIn, urandomBuffer); ... }
通過測試可以發現,hotspot需要使用配置項"-Djava.security.egd=file:/dev/./urandom"才能從urandom讀取數據,這裏openjdk做了優化,直接從urandom讀取數據。
/dev/random在產生大量隨機數的時候比/dev/urandom慢,所以,建議在大量使用隨機數的時候,將隨機數發生器指定爲/dev/./urandom。
注意:jvm參數值爲/dev/./urandom而不是/dev/urandom,這裏是jdk的一個bug引起。
bug產生的原因請注意下面第四行源碼,如果java.security.egd參數指定的是file:/dev/random或者file:/dev/urandom,則調用了無參的NativeSeedGenerator構造函數,而無參的構造函數將默認使用file:/dev/random 。openjdk的代碼和hotspot的代碼已經不同,openjdk在後續產生隨機數的時候沒有使用這個變量。
abstract class SeedGenerator { ...... static { String egdSource = SunEntries.getSeedSource(); if (egdSource.equals(URL_DEV_RANDOM) || egdSource.equals(URL_DEV_URANDOM)) { try { instance = new NativeSeedGenerator(); if (debug != null) { debug.println("Using operating system seed generator"); } } catch (IOException e) { if (debug != null) { debug.println("Failed to use operating system seed " + "generator: " + e.toString()); } } } else if (egdSource.length() != 0) { try { instance = new URLSeedGenerator(egdSource); if (debug != null) { debug.println("Using URL seed generator reading from " + egdSource); } } catch (IOException e) { if (debug != null) debug.println("Failed to create seed generator with " + egdSource + ": " + e.toString()); } } ...... }