-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
ThreadLocalRandomProxy.java
50 lines (40 loc) · 1.33 KB
/
ThreadLocalRandomProxy.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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 {
private interface Provider {
Random current();
}
/**
* To avoid NoClassDefFoundError during loading {@link ThreadLocalRandomProxy}
*/
private static class JdkProvider implements Provider {
@Override
public Random current() {
return java.util.concurrent.ThreadLocalRandom.current();
}
}
private static class InternalProvider implements Provider {
@Override
public Random current() {
return ThreadLocalRandom.current();
}
}
private static final Provider INSTANCE = getThreadLocalProvider();
private static Provider getThreadLocalProvider() {
try {
final JdkProvider jdkProvider = new JdkProvider();
jdkProvider.current(); // To make sure that ThreadLocalRandom actually exists in the JDK
return jdkProvider;
} catch (Throwable e) {
return new InternalProvider();
}
}
public static Random current() {
return INSTANCE.current();
}
}