Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Trivia! Lru Cache impl

DZone's Guide to

Trivia! Lru Cache impl

· Database Zone ·
Free Resource

RavenDB vs MongoDB: Which is Better? This White Paper compares the two leading NoSQL Document Databases on 9 features to find out which is the best solution for your next project.  


It has been a while since I actually posted some code here, and I thought that this implementation was quite nice, in that it is simple & works for what it needs to do.

    public class LruCache<TKey, TValue>
    {
        private readonly int _capacity;
        private readonly Stopwatch _stopwatch = Stopwatch.StartNew();
     
        private class Node
        {
            public TValue Value;
            public volatile Reference<long> Ticks;
       }
    
       private readonly ConcurrentDictionary<TKey, Node> _nodes = new ConcurrentDictionary<TKey, Node>();
    
       public LruCache(int capacity)
       {
           Debug.Assert(capacity > 10);
           _capacity = capacity;
       }
    
       public void Set(TKey key, TValue value)
       {
           var node = new Node
           {
               Value = value,
               Ticks = new Reference<long> { Value = _stopwatch.ElapsedTicks }
           };
    
           _nodes.AddOrUpdate(key, node, (_, __) => node);
           if (_nodes.Count > _capacity)
           {
               foreach (var source in _nodes.OrderBy(x => x.Value.Ticks).Take( nodes.Count / 10))
               {
                   Node _;
                   _nodes.TryRemove(source.Key, out _);
               }
           }
       }
    
       public bool TryGet(TKey key, out TValue value)
       {
           Node node;
           if (_nodes.TryGetValue(key, out node))
           {
               node.Ticks = new Reference<long> {Value = _stopwatch.ElapsedTicks};
               value = node.Value;
               return true;
           }
           value = default(TValue);
           return false;
       } 







Do you pay to use your database? What if your database paid you? Learn more with RavenDB.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}