시작하기무료로 시작하기

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) {}
}
코드 편집 및 실행