sitelink1 | http://ukmie.tistory.com/88 |
---|---|
sitelink2 | |
sitelink3 | |
sitelink4 | |
sitelink5 | |
sitelink6 |
LinkedHashMap 를 이용하여 간단하게 LRU(leat-recently-used) 캐쉬를 구현할 수 있다.
여러가지 캐쉬 알고리즘과 솔루션들을 상황에 따라 고를 수 있지만, 간단한 캐쉬 기능이 필요한 경우
유용하게 쓸수 있다.
·미리보기 | 소스복사·
- import java.util.LinkedHashMap;
- import java.util.Collection;
- import java.util.Map;
- import java.util.ArrayList;
- public class LRUCache
{ - private static final float hashTableLoadFactor = 0.75f;
- private LinkedHashMap
map; - private int cacheSize;
- public LRUCache(int cacheSize) {
- this.cacheSize = cacheSize;
- int hashTableCapacity = (int) Math.ceil(cacheSize / hashTableLoadFactor) + 1;
- map = new LinkedHashMap
(hashTableCapacity, hashTableLoadFactor, true) { // (an anonymous inner class) - private static final long serialVersionUID = 1;
- @Override
- protected boolean removeEldestEntry(Map.Entry
eldest) { - return size() > LRUCache.this.cacheSize;
- }
- };
- }
- /**
- * The retrieved entry becomes the MRU (most recently used) entry.
- */
- public synchronized V get(K key) {
- return map.get(key);
- }
- /**
- * If the cache is full, the LRU (least recently used) entry is dropped.
- */
- 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();
- }
- public synchronized Collection
> getAll() { - return new ArrayList
>(map.entrySet()); - }
- // 4test..!
- public static void main(String[] args) {
- LRUCache
c = new LRUCache(3); - c.put("1", "one"); // 1
- c.put("2", "two"); // 2 1
- c.put("3", "three"); // 3 2 1
- c.put("4", "four"); // 4 3 2
- if (c.get("2") == null)
- throw new Error(); // 2 4 3
- c.put("5", "five"); // 5 2 4
- c.put("4", "second four"); // 4 5 2
- // Verify cache content.
- if (c.usedEntries() != 3)
- throw new Error();
- if (!c.get("4").equals("second four"))
- throw new Error();
- if (!c.get("5").equals("five"))
- throw new Error();
- if (!c.get("2").equals("two"))
- throw new Error();
- // List cache content.
- for (Map.Entry
e : c.getAll()) - System.out.println(e.getKey() + " : " + e.getValue());
- }
- }
참고:
http://www.source-code.biz/snippets/java/6.htm
http://dojeun.egloos.com/317868
http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedHashMap.html