caching - How would you implement an LRU cache in Java? -
please don't ehcache or oscache, etc. assume purposes of question want implement own using sdk (learning doing). given cache used in multithreaded environment, datastructures use? i've implemented 1 using linkedhashmap , collections#synchronizedmap, i'm curious if of new concurrent collections better candidates.
update: reading through yegge's latest when found nugget:
if need constant-time access , want maintain insertion order, can't better linkedhashmap, wonderful data structure. way possibly more wonderful if there concurrent version. alas.
i thinking same thing before went linkedhashmap
+ collections#synchronizedmap
implementation mentioned above. nice know hadn't overlooked something.
based on answers far, sounds best bet highly concurrent lru extend concurrenthashmap using of same logic linkedhashmap
uses.
i lots of these suggestions, think i'll stick linkedhashmap
+ collections.synchronizedmap
. if revisit in future, i'll work on extending concurrenthashmap
in same way linkedhashmap
extends hashmap
.
update:
by request, here's gist of current implementation.
private class lrucache<a, b> extends linkedhashmap<a, b> { private final int maxentries; public lrucache(final int maxentries) { super(maxentries + 1, 1.0f, true); this.maxentries = maxentries; } /** * returns <tt>true</tt> if <code>lrucache</code> has more entries maximum specified when * created. * * <p> * method <em>does not</em> modify underlying <code>map</code>; relies on implementation of * <code>linkedhashmap</code> that, behavior documented in javadoc * <code>linkedhashmap</code>. * </p> * * @param eldest * <code>entry</code> in question; implementation doesn't care is, since * implementation dependent on size of cache * @return <tt>true</tt> if oldest * @see java.util.linkedhashmap#removeeldestentry(map.entry) */ @override protected boolean removeeldestentry(final map.entry<a, b> eldest) { return super.size() > maxentries; } } map<string, string> example = collections.synchronizedmap(new lrucache<string, string>(cache_size));
Comments
Post a Comment