Trivia! Lru Cache impl
Join the DZone community and get the full member experience.
Join For FreeIt 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; }
Cache (computing)
Implementation
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Multi-Stream Joins With SQL
-
Managing Data Residency, the Demo
-
[DZone Survey] Share Your Expertise for Our Database Research, 2023 Edition
-
Java String Templates Today
Comments