JAVA lru缓存的实现思路

时间:2018-10-09 22:47:21

标签: java caching

我正在尝试在Java中实现lru缓存。 我的想法是:

  • 按链接列表的顺序存储缓存元素。
  • 将元素存储在hashMap中以进行相对快速的检查。

我努力将移动元素的一部分实现到缓存的开头。 我的想法是将每个元素从缓存映射到特定的元素迭代器,这样,元素删除将花费O(1)时间,而不是为列表中的元素进行服务,但是由于我的列表不断变化,因此迭代器无用(您只有在完成列表上的所有操作后才能使用它)。

我听说可以在C&C ++中实现这种实现,有什么方法可以在JAVA中实现上述想法?

你们中的任何人都可以建议一种实现上述目的的方法(不使用其他数据结构,如LinkedHashMap,仅linkedList和常规hashMap)吗?

感谢进阶!

编辑

到目前为止,这是代码-假设bookId是我正在缓存的内容。

更改列表后,失败的操作全部是iterator.next()。

private HashMap<String, ListIterator> fromBookNameToIteraot = new HashMap<>();
    private LinkedList<Integer> queue = new LinkedList<>();
    private HashMap<Integer, String> fromBookIdToBookName = new HashMap<>();
    private Iterator<Integer> iterator = queue.listIterator(0);
    private static int bookObjectID = 0;
    private int cacheSize;
    //Ctor
    public LRUCache(int cacheSize) {
        this.cacheSize = cacheSize;
    }

    public void access(String i_BookName){
        int tempBook = 0;
        //In case the requested book in cache (in our map) - O(1) remove operation
        if (fromBookNameToIteraot.containsKey(i_BookName)){
            iterator = fromBookNameToIteraot.get(i_BookName);
            //Validate the queue is not empty, then remove the one from the map
            if(iterator.hasNext()){
                tempBook = iterator.next();
                iterator.remove();
            }
            queue.addFirst(tempBook);
            iterator = queue.listIterator(0);
            fromBookNameToIteraot.put(i_BookName, (ListIterator) iterator);
            return;
        }
        /*
        *In this case the book is not in cache, and the cache is full
        * - get the last book element from queue as least recently used, and remove it.
        * - get the book name (since i don't have DB i used another map to fetch bookName from book object.
        * - delete the book from the cache map.
        * - insert the new book to cache
        * */
        else if(queue.size() == cacheSize) {
            int bookToDel = queue.getLast();
            queue.removeLast();
            String bookNameToDel = fromBookIdToBookName.get(bookToDel);
            fromBookNameToIteraot.remove(bookNameToDel);
            fromBookIdToBookName.remove(bookToDel);
        }

        queue.addFirst(bookObjectID);
        iterator = queue.listIterator(0);
        fromBookNameToIteraot.put(i_BookName, (ListIterator) iterator);
        fromBookIdToBookName.put(bookObjectID, i_BookName);
        bookObjectID++;
    }

0 个答案:

没有答案