Skip to content
This repository has been archived by the owner on May 22, 2019. It is now read-only.

Commit

Permalink
IdGenerator is made Java6 execution environment compatible. On Java 7…
Browse files Browse the repository at this point in the history
…+, where ThreadLocalRandom is available, it would use that via introspection.
  • Loading branch information
alex-vas committed Aug 24, 2016
1 parent c6c8534 commit be4f3c0
Showing 1 changed file with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,39 @@
package ws.wamp.jawampa.internal;

import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.Random;

/**
* Contains method for generating WAMP IDs
*/
public class IdGenerator {

private static Random oldRandom;

private static Class<?> threadLocalRandomClass;

private static Random getRandomGenerator()
{
if (oldRandom == null && threadLocalRandomClass == null) {

This comment has been minimized.

Copy link
@the20login

the20login Aug 25, 2016

How about extract this check to static initializer?

This comment has been minimized.

Copy link
@alex-vas

alex-vas Aug 25, 2016

Author

Can do I suppose... Having said that, once those two fields are in CPU cache, this little if statement would not affect the performance that much, if at all.

try {
threadLocalRandomClass = ClassLoader.getSystemClassLoader().loadClass("java.util.concurrent.ThreadLocalRandom"); // Java 7+
}
catch (ClassNotFoundException e) {
// fall back to an old, Java 6, low performance Random().
oldRandom = new Random();
}
}
if (threadLocalRandomClass != null) {
try {
return (Random) threadLocalRandomClass.getMethod("current").invoke(null);
}
catch (Exception e) {
throw new IllegalStateException(e);
}
}
return oldRandom;
}

/**
* Generates a new ID through a random generator.<br>
* If the new ID is not valid or is already in use as a key in the provided Map
Expand All @@ -34,7 +60,7 @@ public class IdGenerator {
*/
public static long newRandomId(Map<Long, ?> controlMap) {
for (;;) {
long l = ThreadLocalRandom.current().nextLong();
long l = getRandomGenerator().nextLong();
if (l < IdValidator.MIN_VALID_ID || l > IdValidator.MAX_VALID_ID) continue;
if (controlMap == null || !controlMap.containsKey(l)) return l;
}
Expand Down

0 comments on commit be4f3c0

Please sign in to comment.