我正在编写一个使用LinkedHashMap
. 通常,我需要重写这些方法put
,get
以便在将对象添加到缓存时写入磁盘,如果在缓存中找不到对象,则从磁盘获取。
我的 LRUCache 类看起来像:
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;
}
}
我的问题是如何覆盖这两种方法以尽可能快地完成。缓存对象实现是个好主意Externalize
吗?
谢谢