【问题标题】:Overriding methods for cache implementation缓存实现的覆盖方法
【发布时间】:2012-11-13 11:01:23
【问题描述】:

我正在编写一个使用LinkedHashMap 实现 LRU 缓存的类。通常我需要重写 putget 方法,以便在将对象添加到缓存时写入磁盘并在缓存中找不到对象时从磁盘获取。

我的 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 具有持久性。

标签: java caching


【解决方案1】:

很抱歉,但实际上你必须在这里解决各种问题:

  • 什么是最好/最快的 java 对象序列化?已在其他问题中讨论过。
  • 如何将之前写入的对象更新到文件中?
  • 当需要检索时,如何有效地找到文件中存储对象的字节偏移量?
  • 如何从文件中删除项目并压缩文件?
  • 如何快速写入,避免随机访问硬盘存储?

您在数据库书籍中找到的最后一个问题的所有答案。

如果您只有一个不经常更改的视图对象,并且您想要一个简单的解决方案,只需在每次放置时将 HashMap 序列化到文件中。如果数据很重要,最好总是写入一个新文件,然后删除旧文件,以防止数据丢失。

顺便说一句:在您的示例代码中,缺少存储磁盘对象的删除。

【讨论】:

    猜你喜欢
    • 2012-09-16
    • 1970-01-01
    • 2021-10-11
    • 2015-11-19
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    相关资源
    最近更新 更多