A LRU Cache in 10 Lines of Java

本文介绍了一种使用Java实现的Least Recently Used (LRU) 缓存机制。LRU缓存利用了链表和哈希表的数据结构特性,通过LinkedHashMap来实现缓存淘汰策略。文章还提供了一个简单的LRU缓存类实现。

I had a couple of interviews long ago which asked me to implemented a least recently used (LRU) cache. A cache itself can simply be implemented using a hash table, however adding a size limit gives an interesting twist on the question. Let’s take a look at how we can do this.

Least Recently Used Cache Eviction

To accomplish cache eviction we need to be easily able to:

  • query the last recently used item

  • mark an item as the most recently used item

A linked list allows for both operations. Checking for the least recently used item can just return the tail. Marking an item as recently used can be simply removing it from its current position and moving it to the head. The missing puzzle piece is finding this item in the linked list quickly.

Hash tables to the rescue

Looking into our data structure toolbox, hash tables allow us to easily index an object in (amortized) constant time. If we create a hash table from key -> list node, we can find the most recently used node in constant time. The converse is true in that we can also still check for the existence (or lack-there-of) in constant time as well.

After looking up the node we can then move it to the front of the linked list to mark it as the most recently used item.

The Java shortcut

Sometimes knowing less common data structures from the standard library of various programming languages can prove to be of help. Given this hybrid data structure we would have to implement a hash table on top of a linked list. However Java already provides this for us in the form of a LinkedHashMap! It even provides an overridable eviction policy method (removeEldestEntry docs). The only catch is that by default the linked list order is the insertion order, not access. However one of the constructor exposes an option use the access order instead (docs).

Without further ado:

import java.util.LinkedHashMap;
import java.util.Map;
 
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
  private int cacheSize;
 
  public LRUCache(int cacheSize) {
    super(16,  0.75f, true);
    this.cacheSize = cacheSize;
  }
 
  protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
    return size() >= cacheSize;
  }
}


转载于:https://my.oschina.net/u/553266/blog/479096

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值