diff Implab/Components/LazyAndWeak.cs @ 180:c32688129f14 ref20160224

refactoring complete, JSONParser rewritten
author cin
date Thu, 24 Mar 2016 02:30:46 +0300
parents d5c5db0335ee
children 76e8f2ba12b8
line wrap: on
line diff
--- a/Implab/Components/LazyAndWeak.cs	Wed Mar 23 19:52:08 2016 +0300
+++ b/Implab/Components/LazyAndWeak.cs	Thu Mar 24 02:30:46 2016 +0300
@@ -2,6 +2,13 @@
 using System.Threading;
 
 namespace Implab.Components {
+    /// <summary>
+    /// Creates an instace on-demand and allows it to be garbage collected.
+    /// </summary>
+    /// <remarks>
+    /// Usefull when dealing with memory-intensive objects which are frequently used.
+    /// This class is similar to <see cref="ObjectPool{T}"/> except is a singleton.
+    /// </remarks>
     public class LazyAndWeak<T> where T : class {
 
         readonly Func<T> m_factory;
@@ -35,6 +42,18 @@
                         if (Interlocked.CompareExchange(ref m_reference, new WeakReference(value), weak) == weak)
                             return value;
                     } else {
+                        lock (m_lock) {
+                            // double check
+                            if (weak != null) {
+                                value = weak.Target as T;
+                                if (value != null)
+                                    return value;
+                            }
+                            // we are safe to write
+                            value = m_factory();
+                            m_reference = new WeakReference(value);
+                            return value;
+                        }
                     }
                 }
             }