Following answer is taken from http://stackoverflow.com/questions/221525/how-would-you-implement-an-lru-cache-in-java-6


private class LruCache extends LinkedHashMap {
private final int maxEntries;

public LruCache(final int maxEntries) {
super(maxEntries + 1, 1.0f, true);
this.maxEntries = maxEntries;
}

/**
* Returns true if this LruCache has more entries than the maximum specified when it was
* created.
*
*

* This method does not modify the underlying Map; it relies on the implementation of
* LinkedHashMap to do that, but that behavior is documented in the JavaDoc for
* LinkedHashMap.
*

*
* @param eldest
* the Entry in question; this implementation doesn't care what it is, since the
* implementation is only dependent on the size of the cache
* @return true if the oldest
* @see java.util.LinkedHashMap#removeEldestEntry(Map.Entry)
*/
@Override
protected boolean removeEldestEntry(final Map.Entry
eldest) {
return super.size() > maxEntries;
}
}

Map example = Collections.synchronizedMap(new LruCache(CACHE_SIZE));

Advertisements