1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.turbo.lru;
15
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.LinkedList;
19 import java.util.List;
20
21
22
23
24
25
26
27 public class T_LRUCache<K> {
28
29 int sequenceNumber;
30 final int cacheSize;
31 List<T_Entry<K>> cacheList = new LinkedList<T_Entry<K>>();
32
33 public T_LRUCache(int size) {
34 this.cacheSize = size;
35 }
36
37 synchronized public void put(K k) {
38 sequenceNumber++;
39 T_Entry<K> te = getEntry(k);
40 if (te != null) {
41 te.sequenceNumber = sequenceNumber;
42 } else {
43 te = new T_Entry<K>(k, sequenceNumber);
44 cacheList.add(te);
45 }
46 Collections.sort(cacheList);
47 while (cacheList.size() > cacheSize) {
48 cacheList.remove(0);
49 }
50 }
51
52 synchronized public K get(K k) {
53 T_Entry<K> te = getEntry(k);
54 if (te == null) {
55 return null;
56 } else {
57 te.sequenceNumber = ++sequenceNumber;
58 Collections.sort(cacheList);
59 return te.k;
60 }
61 }
62
63 synchronized public List<K> keyList() {
64 List<K> keyList = new ArrayList<K>();
65 for (T_Entry<K> e : cacheList) {
66 keyList.add(e.k);
67 }
68 return keyList;
69 }
70
71 private T_Entry<K> getEntry(K k) {
72 for (int i = 0; i < cacheList.size(); i++) {
73 T_Entry<K> te = cacheList.get(i);
74 if (te.k.equals(k)) {
75 return te;
76 }
77 }
78 return null;
79 }
80
81 public void dump() {
82 System.out.print("T:");
83 for (T_Entry<K> te : cacheList) {
84
85 System.out.print(te.k + ", ");
86 }
87 System.out.println();
88 }
89
90 }