20
20
21
21
import java .util .Random ;
22
22
23
+ import javax .annotation .Nullable ;
24
+
23
25
import org .apiguardian .api .API ;
24
26
import org .apiguardian .api .API .Status ;
25
27
28
30
29
31
import edu .umd .cs .findbugs .annotations .SuppressFBWarnings ;
30
32
33
+ import com .navercorp .fixturemonkey .api .container .ConcurrentLruCache ;
34
+
31
35
/**
32
36
* Reference jqwik SourceOfRandomness
33
37
*/
@@ -37,6 +41,7 @@ public abstract class Randoms {
37
41
private static final boolean USE_JQWIK_ENGINE ;
38
42
private static final ThreadLocal <Random > CURRENT = new ThreadLocal <>();
39
43
private static final ThreadLocal <Long > SEED = new ThreadLocal <>();
44
+ private static final ConcurrentLruCache <Long , Random > CACHED_SEED = new ConcurrentLruCache <>(5 );
40
45
41
46
static {
42
47
boolean useJqwikEngine ;
@@ -50,20 +55,24 @@ public abstract class Randoms {
50
55
}
51
56
52
57
public static Random create (String seed ) {
53
- if (USE_JQWIK_ENGINE ) {
54
- SEED .set (Long .parseLong (seed ));
55
- return SourceOfRandomness .create (seed );
56
- }
57
-
58
+ long longSeed ;
58
59
try {
59
- long actualSeed = Long .parseLong (seed );
60
- Random random = newRandom (actualSeed );
61
- CURRENT .set (random );
62
- SEED .set (actualSeed );
63
- return random ;
60
+ longSeed = Long .parseLong (seed );
64
61
} catch (NumberFormatException nfe ) {
65
62
throw new JqwikException (String .format ("[%s] is not a valid random seed." , seed ));
66
63
}
64
+
65
+ return CACHED_SEED .computeIfAbsent (longSeed , l -> {
66
+ if (USE_JQWIK_ENGINE ) {
67
+ SEED .set (longSeed );
68
+ return SourceOfRandomness .create (seed );
69
+ }
70
+
71
+ Random random = newRandom (longSeed );
72
+ CURRENT .set (random );
73
+ SEED .set (longSeed );
74
+ return random ;
75
+ });
67
76
}
68
77
69
78
public static Random current () {
@@ -72,14 +81,20 @@ public static Random current() {
72
81
: CURRENT .get ();
73
82
}
74
83
75
- public static long currentSeed () {
84
+ @ Nullable
85
+ public static Long currentSeed () {
76
86
return SEED .get ();
77
87
}
78
88
79
89
public static int nextInt (int bound ) {
80
90
return current ().nextInt (bound );
81
91
}
82
92
93
+ public static void clear () {
94
+ SEED .remove ();
95
+ CURRENT .remove ();
96
+ }
97
+
83
98
private static Random newRandom (final long seed ) {
84
99
return USE_JQWIK_ENGINE
85
100
? SourceOfRandomness .newRandom (seed )
0 commit comments