Skip to content

Commit

Permalink
Support the JDK's ThreadLocalRandom
Browse files Browse the repository at this point in the history
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
arteam committed Feb 4, 2017
1 parent 5d98a2b commit 406d280
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
Expand Up @@ -95,7 +95,7 @@ public void update(long value, long timestamp) {
try {
final double itemWeight = weight(timestamp - startTime);
final WeightedSample sample = new WeightedSample(value, itemWeight);
final double priority = itemWeight / ThreadLocalRandom.current().nextDouble();
final double priority = itemWeight / ThreadLocalRandomProxy.current().nextDouble();

final long newCount = count.incrementAndGet();
if (newCount <= size) {
Expand Down
@@ -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();
}

}
Expand Up @@ -70,7 +70,7 @@ public void update(long value) {
private static long nextLong(long n) {
long bits, val;
do {
bits = ThreadLocalRandom.current().nextLong() & (~(1L << BITS_PER_LONG));
bits = ThreadLocalRandomProxy.current().nextLong() & (~(1L << BITS_PER_LONG));
val = bits % n;
} while (bits - val + (n - 1) < 0L);
return val;
Expand Down

0 comments on commit 406d280

Please sign in to comment.