Created
July 27, 2011 12:54
-
-
Save ayende/1109303 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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