The ConcurrentHashQueue data structure is a FIFO queue that at the same time allows look-ups of items based on a key in O(1) like a dictionary. It can be used as a cache when the number of cached items is a constant and the eviction strategy is FIFO. This makes sense when the cost of computing/creating an evicted item is not so high to justify the book-keeping costs of a LRU cache.This implementation is also intended to be thread-safe.internal class ConcurrentHashQueue<TKey, TValue>{    private readonly object _syncRoot = new object();    private readonly int _capacity;    private readonly Dictionary<TKey, TValue> _map;    private readonly Queue<TKey> _queue;    public ConcurrentHashQueue(int capacity)    {        _capacity = capacity;        _map = new Dictionary<TKey, TValue>(capacity);        _queue = new Queue<TKey>(capacity);    }    public TValue GetOrAdd(TKey key, Func<TValue> createValue)    {        TValue value;        // first try to get the value without locking        // ReSharper disable once InconsistentlySynchronizedField        if (_map.TryGetValue(key, out value))        {            return value;        }        // the value needs to be created and added        lock (_syncRoot)        {            // recheck existence within critical section to avoid racing conditions            if (_map.TryGetValue(key, out value))            {                return value;            }            value = createValue();            Add(key, value);        }        return value;    }    private void Add(TKey key, TValue value)    {        if (_map.Count == _capacity) // capacity reached        {            RemoveFirst();        }        _map.Add(key, value);        _queue.Enqueue(key);        Debug.Assert(_map.Count == _queue.Count, The count of the queue should always equal to the count of the map.);        Debug.Assert(_map.Count <= _capacity, The count of items should never exceed the capacity.);    }    private void RemoveFirst()    {        TKey first = _queue.Dequeue();        _map.Remove(first);    }}
ConcurrentHashQueue in C#
c#;concurrency;cache
You call this a Queue but it does not behave like one. It's more like a strange dictionary that removes the first element that was added if the capacity exceeds. A queue would have such methods as Enqueue and Dequeue for adding and getting elements but in this queue I need to know the key of an element in order to get it so there is no way of getting the first added element. A name like FixedCapacityCollection would be more appropriate.Since this is a collection your class should also implement the IEnumerable<KeyValuePair<TKey, TValue>> interface so that it can be used with linq and loops if necessary.