summary refs log tree commit diff
path: root/crypto/src/util/Objects.cs
diff options
context:
space:
mode:
Diffstat (limited to 'crypto/src/util/Objects.cs')
-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;
+        }
     }
 }