【发布时间】:2012-11-13 11:01:23
【问题描述】:
我正在编写一个使用LinkedHashMap 实现 LRU 缓存的类。通常我需要重写 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是个好主意吗?
谢谢
【问题讨论】:
-
除非迫不得已,否则请不要重新发明轮子。使用 Guava 缓存支持。它重量轻且线程安全。
-
Guava 存储的数据不会超过 RAM 的容量。 Guava 缓存在应用程序的单次运行中是本地的,因此它们不会将数据存储在文件中。
-
天哪,我没有看到
File。 不要不要那样做! 你应该看看像 Ehcache 之类的东西(或 memcache 或 redis 或无数已经这样做的东西)。认真不要编写自己的分布式缓存。这不是一个简单的问题,需要考虑大量的并发问题。 -
@AdamGent:感谢您的建议。我认为 JCS 是最适合我的选择,但我找不到它是否持久,你知道吗?
-
我只用过Guava的缓存支持,Ehcache和Redis。我很久以前使用过memcache。 Redis 是持久的,但它不仅仅是缓存。 Ehcache 具有持久性。