Skip to content

Commit a892069

Browse files
authored
Use in-code lazy initialization for LazyRandom (for compatibility with native code generation tools) (#85)
1 parent 196b138 commit a892069

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

src/main/java/com/fasterxml/uuid/impl/LazyRandom.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,26 @@
99
*/
1010
public final class LazyRandom
1111
{
12-
private final static SecureRandom shared = new SecureRandom();
12+
private static final Object lock = new Object();
13+
private static volatile SecureRandom shared;
1314

1415
public static SecureRandom sharedSecureRandom() {
15-
return shared;
16+
// Double check lazy initialization idiom (Effective Java 3rd edition item 11.6)
17+
// Use so that native code generation tools do not detect a SecureRandom instance in a static final field.
18+
SecureRandom result = shared;
19+
20+
if (result != null) {
21+
return result;
22+
}
23+
24+
synchronized (lock) {
25+
result = shared;
26+
27+
if (result == null) {
28+
result = shared = new SecureRandom();
29+
}
30+
31+
return result;
32+
}
1633
}
1734
}

0 commit comments

Comments
 (0)