Over a million developers have joined DZone.

Trivia! Lru Cache impl

· Database Zone

Sign up for the Couchbase Community Newsletter to stay ahead of the curve on the latest NoSQL news, events, and webinars. Brought to you in partnership with Coucbase.


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;
       } 







The Getting Started with NoSQL Guide will get you hands-on with NoSQL in minutes with no coding needed. Brought to you in partnership with Couchbase.

Topics:

Published at DZone with permission of Ayende Rahien, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}