I'm writting a Class that implements an LRU cache with a LinkedHashMap. Typically I would need to override the methods put and get in order to write to disk when an object is added to the cache and fetch from disk if the object is not found in the cache.
My LRUCache class looks like:
public class LRUCache<K, V> extends LinkedHashMap<K, V>
implements Serializable {
/**
* File where the elements of the cache are stored
*/
private File cacheFile = null;
/**
* UID of the class for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Maximum number of entries in the cache.
*/
private final int maxEntries;
/**
* Default constructor of the cache.
*
* @param newMaxEntries
* the maximum number of entries in the cache.
*/
public LRUCache(final int newMaxEntries, String fileName) {
super(newMaxEntries + 1, 1.0f, true);
this.maxEntries = newMaxEntries;
this.cacheFile = new File(fileName);
}
@Override
public V get(Object key) {
V VObject = super.get(key);
if (VObject == null) {
// TODO: Fetch from disk
}
return VObject;
}
@Override
public V put(K key, V value) {
// TODO: Write to disk
return super.put(key, value);
}
@Override
protected final boolean
removeEldestEntry(final Map.Entry<K, V> eldest) {
return super.size() > maxEntries;
}
}
My question is how I can override these two methods to do it as fastest as possible. Would it be a good idea that the cached objects implement Externalize?
Thanks
File. Holy crap don't don't do that! You should look at something like Ehcache (or memcache or redis or the myriad of things that already do this). Seriously don't write your own distributed cache. It is not an easy problem and there are tons of concurrency issues to consider.