Skip to content

Instantly share code, notes, and snippets.

@ayende
Created July 27, 2011 12:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayende/1109303 to your computer and use it in GitHub Desktop.
Save ayende/1109303 to your computer and use it in GitHub Desktop.
public class ConcurrentLeastFrequentlyUse<T> where T : class
{
private readonly int[] generationSizes;
private readonly ConcurrentQueue<T>[] queues;
public ConcurrentLeastFrequentlyUse(params int[] generationSizes)
{
this.generationSizes = generationSizes;
queues =new ConcurrentQueue<T>[generationSizes.Length];
}
public event Action<T> ItemDropped;
internal void InvokeItemDropped(T item)
{
var handler = ItemDropped;
if (handler != null)
handler(item);
}
public void Use(T item)
{
queues[0].Enqueue(item);
T lastItem = null;
for (int i = 0; i < generationSizes.Length; i++)
{
if (queues[i].Count <= generationSizes[i])
continue;
if (!queues[i].TryDequeue(out lastItem))
continue;
if ((i + 1) >= generationSizes.Length)
break;
queues[i + 1].Enqueue(lastItem);
lastItem = default(T);
}
if(lastItem != default(T))
InvokeItemDropped(lastItem);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment