Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Modified the cache to use a more efficient way to iterate through and…

… check each weak reference
  • Loading branch information...
commit d2eaf9a74ba854914bb834f2e2d5814a6bfa7fea 1 parent 1be0a59
@GWBasic authored
View
93 Server/ObjectCloud.Common/Cache.cs
@@ -71,18 +71,13 @@ public class Cache<TKey, TValue, TConstructorArg> : Cache
/// <summary>
/// The GC count that was present at the last cleanup, used to prevent duplicate cleanups
- /// </summary>
+ /// </summary>
private int _GCCountAtLastCleanup = GC.CollectionCount(GC.MaxGeneration);
/// <summary>
- /// A copy of all of the weak references, used to periodically check to see if a value is GCed
- /// </summary>
- private WeakReference[] _WRsCopy = new WeakReference[0];
-
- /// <summary>
- /// The mod of the is the current weak reference to check on accessing the cache
+ /// All of the weak references as they are added. This queue is used to allow each operation to look at a weak refernence to eventually detect when the cache needs to be cleaned
/// </summary>
- private int _WRCtr = 0;
+ private LockFreeQueue<WeakReference> _ScanQueue = new LockFreeQueue<WeakReference>();
public Cache(CreateForCache<TKey, TValue, TConstructorArg> createForCache)
{
@@ -106,41 +101,43 @@ public bool Enabled
/// </summary>
private void CheckForCleanup()
{
- if (0 == _WRsCopy.Length)
- return;
+ WeakReference wr;
+ if (_ScanQueue.Dequeue(out wr))
+ {
+ // Keep re-queuing items that are still alive
+ if (wr.IsAlive)
+ _ScanQueue.Enqueue(wr);
+
+ else if (_GCCountAtLastCleanup != GC.CollectionCount(GC.MaxGeneration))
+ ThreadPool.QueueUserWorkItem(DoCleanup);
+ }
+ }
- int wrCtr = Interlocked.Increment(ref _WRCtr) % _WRsCopy.Length;
+ private void DoCleanup(object state)
+ {
+ Lock.EnterWriteLock();
- if (!_WRsCopy[wrCtr].IsAlive)
- ThreadPool.QueueUserWorkItem(delegate(object state)
+ try
+ {
+ // Keep scanning while GCs are running
+ while (_GCCountAtLastCleanup != GC.CollectionCount(GC.MaxGeneration))
{
- Lock.EnterWriteLock();
+ _GCCountAtLastCleanup = GC.CollectionCount(GC.MaxGeneration);
- try
+ foreach (KeyValuePair<TKey, WeakReference> kvp in new Dictionary<TKey, WeakReference>(Dictionary))
{
- // Keep scanning while GCs are running
- while (_GCCountAtLastCleanup != GC.CollectionCount(GC.MaxGeneration))
- {
- _GCCountAtLastCleanup = GC.CollectionCount(GC.MaxGeneration);
-
- foreach (KeyValuePair<TKey, WeakReference> kvp in new Dictionary<TKey, WeakReference>(Dictionary))
- {
- TKey key = kvp.Key;
- WeakReference wr = kvp.Value;
+ TKey key = kvp.Key;
+ WeakReference wr = kvp.Value;
- if (!wr.IsAlive)
- Dictionary.Remove(key);
- }
-
- _WRsCopy = new WeakReference[Dictionary.Count];
- Dictionary.Values.CopyTo(_WRsCopy, 0);
- }
- }
- finally
- {
- Lock.ExitWriteLock();
+ if (!wr.IsAlive)
+ Dictionary.Remove(key);
}
- });
+ }
+ }
+ finally
+ {
+ Lock.ExitWriteLock();
+ }
}
/// <summary>
@@ -191,8 +188,7 @@ public TValue Get(TKey key, TConstructorArg constructorArg)
weakReference = new WeakReference(null);
Dictionary[key] = weakReference;
- _WRsCopy = new WeakReference[Dictionary.Count];
- Dictionary.Values.CopyTo(_WRsCopy, 0);
+ _ScanQueue.Enqueue(weakReference);
}
}
finally
@@ -245,10 +241,10 @@ public void Set(TKey key, TValue value)
weakReference.Target = value;
else
{
- Dictionary[key] = new WeakReference(value);
+ weakReference = new WeakReference(value);
+ Dictionary[key] = weakReference;
- _WRsCopy = new WeakReference[Dictionary.Count];
- Dictionary.Values.CopyTo(_WRsCopy, 0);
+ _ScanQueue.Enqueue(weakReference);
}
}
finally
@@ -283,8 +279,7 @@ public bool Remove(TKey key)
Dictionary.Remove(key);
- _WRsCopy = new WeakReference[Dictionary.Count];
- Dictionary.Values.CopyTo(_WRsCopy, 0);
+ // No effort is made to remove from _ScanQueue because it'll eventually be cleaned up
}
finally
{
@@ -323,7 +318,7 @@ public void Clear()
Dictionary.Clear();
- _WRsCopy = new WeakReference[0];
+ _ScanQueue = new LockFreeQueue<WeakReference>();
}
finally
{
@@ -343,8 +338,6 @@ public IEnumerable<TValue> Values
Lock.EnterReadLock();
try
{
- CheckForCleanup();
-
toEnumerate = Enumerable<WeakReference>.FastCopy(Dictionary.Values);
}
finally
@@ -352,12 +345,20 @@ public IEnumerable<TValue> Values
Lock.ExitReadLock();
}
+ bool queuedCleanup = false;
foreach (WeakReference weakReference in toEnumerate)
{
object toYield = weakReference.Target;
if (null != toYield)
yield return (TValue)toYield;
+
+ // This is done instead of calling CheckForCleanup because each WR is checked
+ else if (!queuedCleanup)
+ {
+ queuedCleanup = true;
+ ThreadPool.QueueUserWorkItem(DoCleanup);
+ }
}
}
}
View
388 Server/ObjectCloud.Common/Threading/LockFreeQueue.cs
@@ -1,195 +1,195 @@
-// See http://www.boyet.com/Articles/LockFreeRedux.html
-
-/*
-Copyright (c) 2010 Julian M Bucknall
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software
-and associated documentation files (the "Software"), to deal in the Software without restriction,
-including without limitation the rights to use, copy, modify, merge, publish, distribute,
-sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or
-substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
-PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-// Note: Contains modifications by Andrew Rondeau for ObjectCloud
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Threading;
-
-namespace ObjectCloud.Common.Threading
-{
- public class LockFreeQueue<T>
- {
-
- SingleLinkNode<T> Head;
- SingleLinkNode<T> Tail;
-
- public LockFreeQueue(IEnumerable<T> items)
- :this()
- {
- foreach (T t in items)
- Enqueue(t);
- }
-
- public LockFreeQueue()
- {
- Head = new SingleLinkNode<T>();
- Tail = Head;
- }
-
- public virtual void Enqueue(T item)
- {
- SingleLinkNode<T> oldTail = null;
- SingleLinkNode<T> oldTailNext;
-
- SingleLinkNode<T> newNode = new SingleLinkNode<T>();
- newNode.Item = item;
-
- bool newNodeWasAdded = false;
- while (!newNodeWasAdded)
- {
- oldTail = Tail;
- oldTailNext = oldTail.Next;
-
- if (Tail == oldTail)
- {
- if (oldTailNext == null)
- newNodeWasAdded = SyncMethods.CAS<SingleLinkNode<T>>(ref Tail.Next, null, newNode);
- else
- SyncMethods.CAS<SingleLinkNode<T>>(ref Tail, oldTail, oldTailNext);
- }
- }
-
- if (Head == Interlocked.CompareExchange<SingleLinkNode<T>>(ref Tail, newNode, oldTail))
- if (null != ItemAddedToEmptyQueue)
- ItemAddedToEmptyQueue(this, new EventArgs());
-
- }
-
- public void EnqueueAll(IEnumerable<T> items)
- {
- foreach (T item in items)
- Enqueue(item);
- }
-
- /// <summary>
- /// Occurs whenever an item is added to an empty queue. This is useful for starting threads that run while a queue has items
- /// </summary>
- public event EventHandler<LockFreeQueue<T>, EventArgs> ItemAddedToEmptyQueue;
-
- public virtual bool Dequeue(out T item)
- {
- item = default(T);
- SingleLinkNode<T> oldHead = null;
- SingleLinkNode<T> oldHeadNext;
-
- bool haveAdvancedHead = false;
- while (!haveAdvancedHead)
- {
-
- oldHead = Head;
- SingleLinkNode<T> oldTail = Tail;
- oldHeadNext = oldHead.Next;
-
- if (oldHead == Head)
- {
- if (oldHead == oldTail)
- {
- if (oldHeadNext == null)
- {
- return false;
- }
- SyncMethods.CAS<SingleLinkNode<T>>(ref Tail, oldTail, oldHeadNext);
- }
-
- else
- {
- item = oldHeadNext.Item;
- haveAdvancedHead =
- SyncMethods.CAS<SingleLinkNode<T>>(ref Head, oldHead, oldHeadNext);
- }
- }
- }
- return true;
- }
-
- public T Dequeue()
- {
- T result;
- Dequeue(out result);
- return result;
- }
-
- /// <summary>
- /// Unreliable way to filter out items from the queue. This may not accurately filter around the head or tail. This function is not thread safe, but hopefully it won't explode if insertions and deletions happen while this is near the head or tail
- /// </summary>
- /// <param name="filter">
- /// A <see cref="GenericArgumentReturn<T, System.Boolean>"/>
- /// </param>
- public void ScanForRemoval(GenericArgumentReturn<T, bool> filter)
- {
- SingleLinkNode<T> cur = Head;
-
- while (null != cur)
- {
- SingleLinkNode<T> next = cur.Next;
-
- if ((cur == Tail) || (next == Tail))
- return;
-
- if (null != next)
- if (!filter(next.Item))
- cur.Next = next.Next;
-
- cur = cur.Next;
- }
- }
- }
-
-
- /// <summary>
- /// Adds a count to the LockFreeQueue
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public class LockFreeQueue_WithCount<T> : LockFreeQueue<T>
- {
- public LockFreeQueue_WithCount() : base() { }
- public LockFreeQueue_WithCount(IEnumerable<T> items) : base(items) { }
-
- /// <summary>
- /// The number of items in the stack. This might be inaccurate if a concurrent thread is pushing or popping, thus it should be treated as an estimate
- /// </summary>
- public long Count
- {
- get { return _Count; }
- }
- private long _Count = 0;
-
- public override void Enqueue(T item)
- {
- base.Enqueue(item);
- Interlocked.Increment(ref _Count);
- }
-
- public override bool Dequeue(out T item)
- {
- bool dequeued = base.Dequeue(out item);
-
- if (dequeued)
- Interlocked.Decrement(ref _Count);
-
- return dequeued;
- }
- }
+// See http://www.boyet.com/Articles/LockFreeRedux.html
+
+/*
+Copyright (c) 2010 Julian M Bucknall
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+and associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+// Note: Contains modifications by Andrew Rondeau for ObjectCloud
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Threading;
+
+namespace ObjectCloud.Common.Threading
+{
+ public class LockFreeQueue<T>
+ {
+
+ SingleLinkNode<T> Head;
+ SingleLinkNode<T> Tail;
+
+ public LockFreeQueue(IEnumerable<T> items)
+ :this()
+ {
+ foreach (T t in items)
+ Enqueue(t);
+ }
+
+ public LockFreeQueue()
+ {
+ Head = new SingleLinkNode<T>();
+ Tail = Head;
+ }
+
+ public virtual void Enqueue(T item)
+ {
+ SingleLinkNode<T> oldTail = null;
+ SingleLinkNode<T> oldTailNext;
+
+ SingleLinkNode<T> newNode = new SingleLinkNode<T>();
+ newNode.Item = item;
+
+ bool newNodeWasAdded = false;
+ while (!newNodeWasAdded)
+ {
+ oldTail = Tail;
+ oldTailNext = oldTail.Next;
+
+ if (Tail == oldTail)
+ {
+ if (oldTailNext == null)
+ newNodeWasAdded = SyncMethods.CAS<SingleLinkNode<T>>(ref Tail.Next, null, newNode);
+ else
+ SyncMethods.CAS<SingleLinkNode<T>>(ref Tail, oldTail, oldTailNext);
+ }
+ }
+
+ if (Head == Interlocked.CompareExchange<SingleLinkNode<T>>(ref Tail, newNode, oldTail))
+ if (null != ItemAddedToEmptyQueue)
+ ItemAddedToEmptyQueue(this, new EventArgs());
+
+ }
+
+ public void EnqueueAll(IEnumerable<T> items)
+ {
+ foreach (T item in items)
+ Enqueue(item);
+ }
+
+ /// <summary>
+ /// Occurs whenever an item is added to an empty queue. This is useful for starting threads that run while a queue has items
+ /// </summary>
+ public event EventHandler<LockFreeQueue<T>, EventArgs> ItemAddedToEmptyQueue;
+
+ public virtual bool Dequeue(out T item)
+ {
+ item = default(T);
+ SingleLinkNode<T> oldHead = null;
+ SingleLinkNode<T> oldHeadNext;
+
+ bool haveAdvancedHead = false;
+ while (!haveAdvancedHead)
+ {
+
+ oldHead = Head;
+ SingleLinkNode<T> oldTail = Tail;
+ oldHeadNext = oldHead.Next;
+
+ if (oldHead == Head)
+ {
+ if (oldHead == oldTail)
+ {
+ if (oldHeadNext == null)
+ {
+ return false;
+ }
+ SyncMethods.CAS<SingleLinkNode<T>>(ref Tail, oldTail, oldHeadNext);
+ }
+
+ else
+ {
+ item = oldHeadNext.Item;
+ haveAdvancedHead =
+ SyncMethods.CAS<SingleLinkNode<T>>(ref Head, oldHead, oldHeadNext);
+ }
+ }
+ }
+ return true;
+ }
+
+ public T Dequeue()
+ {
+ T result;
+ Dequeue(out result);
+ return result;
+ }
+
+ /// <summary>
+ /// Unreliable way to filter out items from the queue. This may not accurately filter around the head or tail. This function is not thread safe, but hopefully it won't explode if insertions and deletions happen while this is near the head or tail
+ /// </summary>
+ /// <param name="filter">
+ /// A <see cref="GenericArgumentReturn<T, System.Boolean>"/>
+ /// </param>
+ public void ScanForRemoval(GenericArgumentReturn<T, bool> filter)
+ {
+ SingleLinkNode<T> cur = Head;
+
+ while (null != cur)
+ {
+ SingleLinkNode<T> next = cur.Next;
+
+ if ((cur == Tail) || (next == Tail))
+ return;
+
+ if (null != next)
+ if (!filter(next.Item))
+ cur.Next = next.Next;
+
+ cur = cur.Next;
+ }
+ }
+ }
+
+
+ /// <summary>
+ /// Adds a count to the LockFreeQueue
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ public class LockFreeQueue_WithCount<T> : LockFreeQueue<T>
+ {
+ public LockFreeQueue_WithCount() : base() { }
+ public LockFreeQueue_WithCount(IEnumerable<T> items) : base(items) { }
+
+ /// <summary>
+ /// The number of items in the stack. This might be inaccurate if a concurrent thread is pushing or popping, thus it should be treated as an estimate
+ /// </summary>
+ public long Count
+ {
+ get { return _Count; }
+ }
+ private long _Count = 0;
+
+ public override void Enqueue(T item)
+ {
+ base.Enqueue(item);
+ Interlocked.Increment(ref _Count);
+ }
+
+ public override bool Dequeue(out T item)
+ {
+ bool dequeued = base.Dequeue(out item);
+
+ if (dequeued)
+ Interlocked.Decrement(ref _Count);
+
+ return dequeued;
+ }
+ }
}
View
70 Server/ObjectCloud.Common/Threading/SingleLinkNode.cs
@@ -1,35 +1,35 @@
-// See http://www.boyet.com/Articles/LockFreeRedux.html
-
-/*
-Copyright (c) 2010 Julian M Bucknall
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software
-and associated documentation files (the "Software"), to deal in the Software without restriction,
-including without limitation the rights to use, copy, modify, merge, publish, distribute,
-sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or
-substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
-PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-// Note: Contains modifications by Andrew Rondeau for ObjectCloud
-
-namespace ObjectCloud.Common.Threading
-{
-
- internal class SingleLinkNode<T>
- {
- // Note; the Next member cannot be a property since it participates in
- // many CAS operations
- public SingleLinkNode<T> Next;
- public T Item;
- }
-}
+// See http://www.boyet.com/Articles/LockFreeRedux.html
+
+/*
+Copyright (c) 2010 Julian M Bucknall
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+and associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+// Note: Contains modifications by Andrew Rondeau for ObjectCloud
+
+namespace ObjectCloud.Common.Threading
+{
+
+ internal class SingleLinkNode<T>
+ {
+ // Note; the Next member cannot be a property since it participates in
+ // many CAS operations
+ public SingleLinkNode<T> Next;
+ public T Item;
+ }
+}
Please sign in to comment.
Something went wrong with that request. Please try again.