Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a proxy which provides a ThreadLocalRandom implementation depending on its availability in runtime. If the JDK provides ThreadLocalRandom, use it. Otherwise, fallback to the internal implementation.
- Loading branch information
Showing
3 changed files
with
39 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
37 changes: 37 additions & 0 deletions
37
metrics-core/src/main/java/com/codahale/metrics/ThreadLocalRandomProxy.java
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 |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package com.codahale.metrics; | ||
|
||
import java.util.Random; | ||
|
||
/** | ||
* Proxy for creating thread local {@link Random} instances depending on the runtime. | ||
* By default it tries to use the JDK's implementation and fallbacks to the internal | ||
* one if the JDK doesn't provide any. | ||
*/ | ||
class ThreadLocalRandomProxy { | ||
|
||
/** | ||
* To avoid NoClassDefFoundError during loading {@link ThreadLocalRandomProxy} | ||
*/ | ||
private static class JdkDelegate { | ||
|
||
private static Random current() { | ||
return java.util.concurrent.ThreadLocalRandom.current(); | ||
} | ||
} | ||
|
||
private static final boolean IS_JDK_THREAD_LOCAL_AVAILABLE = isIsJdkThreadLocalAvailable(); | ||
|
||
private static boolean isIsJdkThreadLocalAvailable() { | ||
try { | ||
JdkDelegate.current(); | ||
return true; | ||
} catch (NoClassDefFoundError e) { | ||
return false; | ||
} | ||
} | ||
|
||
public static Random current() { | ||
return IS_JDK_THREAD_LOCAL_AVAILABLE ? JdkDelegate.current() : ThreadLocalRandom.current(); | ||
} | ||
|
||
} |
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