การสร้าง LRU cache
คุณกำลังพัฒนาเว็บแอปพลิเคชันที่ดึงข้อมูลโปรไฟล์ผู้ใช้ในรูปแบบ string อยู่บ่อยครั้ง เพื่อเพิ่มประสิทธิภาพ จึงต้องการสร้างแคชแบบง่ายสำหรับเก็บข้อมูลโปรไฟล์เหล่านี้ และระบุ entry ที่ถูกใช้งานนานที่สุดได้
คลาส CacheEntry ถูกโหลดไว้ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การปรับแต่งโค้ดใน Java
คำแนะนำการฝึกหัด
- ในเมธอด
get()ให้ดึง entry ของcacheสำหรับkeyที่ระบุ - หลังดึง
keyแล้ว ให้อัปเดตเวลาที่เข้าถึง - หลังเพิ่ม entry ลงในแคชแล้ว ถ้าความจุเกินกำหนด ให้ลบ entry ที่ใช้งานนานที่สุดออก
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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) {}
}