Implementare una cache LRU
Stai sviluppando un'applicazione web che recupera spesso informazioni del profilo utente come stringhe. Per migliorare le prestazioni, vuoi implementare una semplice cache che memorizzi queste stringhe di profilo e sia in grado di identificare quali voci sono state usate meno di recente.
La classe CacheEntry è stata pre-caricata per te.
Questo esercizio fa parte del corso
Ottimizzazione del codice in Java
Istruzioni dell'esercizio
- Nel metodo
get(), recupera la voce dicacheper lakeyspecificata. - Dopo aver recuperato la
key, aggiorna il suo orario di accesso. - Dopo aver inserito una voce nella cache, se la capacità è stata superata, rimuovi la voce meno recentemente utilizzata.
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
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) {}
}