summary refs log tree commit diff
path: root/crypto/src/util
diff options
context:
space:
mode:
authorPeter Dettman <peter.dettman@bouncycastle.org>2023-03-06 16:24:27 +0700
committerPeter Dettman <peter.dettman@bouncycastle.org>2023-03-06 16:24:27 +0700
commit43ae081031d352e05d50a0e9730070d55d075bba (patch)
tree8a4aa308fb1af3e63dad48410a95107672f0fc38 /crypto/src/util
parentRefactor resource loading (diff)
downloadBouncyCastle.NET-ed25519-43ae081031d352e05d50a0e9730070d55d075bba.tar.xz
Refactor singleton initialization
Diffstat (limited to 'crypto/src/util')
-rw-r--r--crypto/src/util/Objects.cs18
1 files changed, 17 insertions, 1 deletions
diff --git a/crypto/src/util/Objects.cs b/crypto/src/util/Objects.cs
index 4d49ac9de..e1ef8c117 100644
--- a/crypto/src/util/Objects.cs
+++ b/crypto/src/util/Objects.cs
@@ -1,4 +1,7 @@
-namespace Org.BouncyCastle.Utilities
+using System;
+using System.Threading;
+
+namespace Org.BouncyCastle.Utilities
 {
     public static class Objects
     {
@@ -6,5 +9,18 @@
         {
             return null == obj ? 0 : obj.GetHashCode();
         }
+
+        internal static TValue EnsureSingletonInitialized<TValue, TArg>(ref TValue value, TArg arg,
+            Func<TArg, TValue> initialize)
+            where TValue : class
+        {
+            TValue currentValue = Volatile.Read(ref value);
+            if (null != currentValue)
+                return currentValue;
+
+            TValue candidateValue = initialize(arg);
+
+            return Interlocked.CompareExchange(ref value, candidateValue, null) ?? candidateValue;
+        }
     }
 }