LRU cache लागू करना
आप एक वेब एप्लिकेशन विकसित कर रहे हैं जो अक्सर यूज़र प्रोफ़ाइल जानकारी को strings के रूप में प्राप्त करता है. परफॉर्मेंस बेहतर करने के लिए, आप एक सिंपल cache लागू करना चाहते हैं जो इन प्रोफ़ाइल strings को स्टोर करे और यह पहचान सके कि कौन-सी एंट्रीज़ सबसे कम हाल में उपयोग हुई थीं.
CacheEntry क्लास आपके लिए पहले से प्रीलोड की गई है.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Java में कोड ऑप्टिमाइज़ करना
अभ्यास निर्देश
get()मेथड में, दिए गएkeyके लिएcacheएंट्री प्राप्त करें.keyप्राप्त करने के बाद, उसका access time अपडेट करें.- किसी एंट्री को cache में रखने के बाद, अगर capacity से अधिक हो जाए तो सबसे कम हाल में उपयोग हुई एंट्री को हटा दें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
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) {}
}