Over a million developers have joined DZone.

Trivia! Lru Cache impl

· Database Zone

Build fast, scale big with MongoDB Atlas, a hosted service for the leading NoSQL database. Try it now! Brought to you in partnership with MongoDB.

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;

Now it's easier than ever to get started with MongoDB, the database that allows startups and enterprises alike to rapidly build planet-scale apps. Introducing MongoDB Atlas, the official hosted service for the database on AWS. Try it now! Brought to you in partnership with MongoDB.


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.

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}