Created
December 28, 2016 03:15
-
-
Save wu-sheng/83235f76371e3b017473c7c6662753de to your computer and use it in GitHub Desktop.
TraceAndSpanIdGenerator From nike.wingtips
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Code from | |
* https://github.com/Nike-Inc/wingtips/blob/38d8ce83207ffee3d638bf7466b8f7058bb36498/wingtips-core/src/main/java/com/nike/wingtips/TraceAndSpanIdGenerator.java#L60 | |
* Thanks to @adriancole | |
*/ | |
public static long generate64BitRandomLong() { | |
byte[] random8Bytes = new byte[8]; | |
random.nextBytes(random8Bytes); | |
return convertBytesToLong(random8Bytes); | |
} | |
protected static long convertBytesToLong(byte[] byteArray) { | |
if (byteArray.length != 8) | |
throw new IllegalArgumentException("byteArray must be 8 bytes in length"); | |
long longVal = 0; | |
for (int i=0; i<8; i++) | |
longVal = (longVal << 8) | (byteArray[i] & 0xff); | |
return longVal; | |
} | |
protected static Random getRandomInstance(String desiredSecureRandomImplementation) { | |
Random randomToUse; | |
try { | |
randomToUse = SecureRandom.getInstance(desiredSecureRandomImplementation); | |
randomToUse.setSeed(System.nanoTime()); | |
} catch (NoSuchAlgorithmException e) { | |
logger.error("Unable to retrieve the {} SecureRandom instance. Defaulting to a new Random(System.nanoTime()) instead. NOTE: This means random longs will not cover " + | |
"the full 64 bits of possible values! See the javadocs for Random.nextLong() for details. dtracer_error=true", desiredSecureRandomImplementation, e); | |
randomToUse = new Random(System.nanoTime()); | |
} | |
return randomToUse; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment