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

Learn how to move from MongoDB to Couchbase Server for consistent high performance in distributed environments at any scale.


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







Want to deliver a whole new level of customer experience? Learn how to make your move from MongoDB to Couchbase Server.

Topics:

Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}