-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
65 lines (52 loc) · 2.02 KB
/
Copy pathLRUCache.java
File metadata and controls
65 lines (52 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package algorithm.lru;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.collections.map.LRUMap;
/**
* @Author : yion
* @Date : 2017. 6. 1.
* @Description : 가장 오랫동안 사용되지 않은 엔트리(호출되지 않는)를 메모리의 후방에 위치하게 하여 메모리에서 삭제 하는 캐싱 알고리즘
* LRU (최근사용우선) 와 비슷한 알고리즘으로 LFU(Least Frequently Used : 참조 횟수 기준) 이 있다.
*/
public class LRUCache<K, V> {
// 용량을 늘릴 때 참고할 값 (몇 프로일 때 용량을 늘릴것인가?)
private static final float hashTableLoadFactor = 0.75f;
// 맵
private LinkedHashMap<K, V> map;
// 캐시 사이즈
private int cacheSize;
public LRUCache(int cacheSize) {
this.cacheSize = cacheSize;
// 3 / 0.75 + 1
int capacity = (int) Math.ceil(cacheSize / hashTableLoadFactor) + 1;
// capacity는 생성할때 map의 크기를 얼마로 할 것인가가? loadFactor는 capacity의 몇 %가 차게되면 용량을 늘려야 할것인가
// 마지막 불리언 값은 정렬을 삽입 순서(false)냐 접근 순서(true)냐에 대한 인자이다
map = new LinkedHashMap<K, V>(capacity, hashTableLoadFactor, true) {
private static final long serialVersionUID = 1;
@Override protected boolean removeEldestEntry (Map.Entry<K, V> eldest) {
return size() > LRUCache.this.cacheSize;
}
};
}
public synchronized V get(K key) {
return map.get(key);
}
public synchronized void put(K key, V value) {
map.put(key, value);
}
public synchronized void clear() {
map.clear();
}
public synchronized int usedEntries() {
return map.size();
}
/**
* 전체 출력
* @return
*/
public synchronized Collection<Map.Entry<K,V>> getAll() {
return new ArrayList<>(map.entrySet());
}
}