This repository has been archived by the owner on May 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
IdGenerator is made Java6 execution environment compatible. On Java 7…
…+, where ThreadLocalRandom is available, it would use that via introspection.
- Loading branch information
Showing
1 changed file
with
28 additions
and
2 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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.
Sorry, something went wrong.
This comment has been minimized.
Sorry, something went wrong.
alex-vas
Author
|
||
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 | ||
|
@@ -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; | ||
} | ||
|
How about extract this check to static initializer?