實作 LRU 快取
你正在開發一個常常需要以字串形式讀取使用者個人檔案資訊的網頁應用程式。為了提升效能,你想實作一個簡單的快取,用來儲存這些個人檔案字串,並能識別哪些項目是最近最少使用的。
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) {}
}