实现 LRU 缓存
您正在开发一款 Web 应用,需要频繁以字符串形式获取用户的个人资料。为提升性能,您希望实现一个简单的缓存,用于存储这些资料字符串,并能识别哪些条目是最近最少使用的。
CacheEntry 类已为您预加载。
本练习是课程的一部分
Java 代码优化
练习说明
- 在
get()方法中,获取指定key的cache条目。 - 取到该
key后,更新其访问时间。 - 将条目放入缓存后,如果超出容量,则移除最近最少使用的条目。
交互式实操练习
通过完成这段示例代码来试试这个练习。
public class StringCache {
private final int capacity = 100;
private final Map cache = new HashMap<>();
public String get(String key) {
// Get the entry for the specified key
CacheEntry entry = ____.get(____);
if (entry == null) return null;
// Update its access time
entry.____();
return entry.value;
}
public void put(String key, String value) {
cache.put(key, new CacheEntry(value));
if (cache.size() > capacity) {
// If capacity exceeded, remove least recently used
____();
}
}
void removeLeastRecentlyUsed() {
String lruKey = null;
long oldest = Long.MAX_VALUE;
for (Map.Entry e : cache.entrySet()) {
if (e.getValue().lastAccessed < oldest) {
oldest = e.getValue().lastAccessed;
lruKey = e.getKey();
}
}
if (lruKey != null) { cache.remove(lruKey); }
}
public static void main(String[] args) {}
}