From 5e7d05374b58db0820ce3971d39e2cec3ae66a18 Mon Sep 17 00:00:00 2001 From: Maia Everett Date: Thu, 12 Oct 2023 19:24:08 +0300 Subject: [PATCH] Use in-code lazy initialization for LazyRandom (for compatibility with native code generation tools) --- .../com/fasterxml/uuid/impl/LazyRandom.java | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/fasterxml/uuid/impl/LazyRandom.java b/src/main/java/com/fasterxml/uuid/impl/LazyRandom.java index 5d53b0f..5e13e41 100644 --- a/src/main/java/com/fasterxml/uuid/impl/LazyRandom.java +++ b/src/main/java/com/fasterxml/uuid/impl/LazyRandom.java @@ -9,9 +9,26 @@ */ public final class LazyRandom { - private final static SecureRandom shared = new SecureRandom(); + private static final Object lock = new Object(); + private static volatile SecureRandom shared; public static SecureRandom sharedSecureRandom() { - return shared; + // Double check lazy initialization idiom (Effective Java 3rd edition item 11.6) + // Use so that native code generation tools do not detect a SecureRandom instance in a static final field. + SecureRandom result = shared; + + if (result != null) { + return result; + } + + synchronized (lock) { + result = shared; + + if (result == null) { + result = shared = new SecureRandom(); + } + + return result; + } } } \ No newline at end of file