-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathLRUEvictionPolicy.java
More file actions
70 lines (60 loc) · 1.93 KB
/
LRUEvictionPolicy.java
File metadata and controls
70 lines (60 loc) · 1.93 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
66
67
68
69
70
package com.lld.inmemorycache.service.impl.policy;
import com.lld.inmemorycache.model.DoublyLinkedList;
import com.lld.inmemorycache.service.EvictionPolicy;
import com.lld.inmemorycache.model.Node;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.concurrent.locks.ReentrantLock;
public class LRUEvictionPolicy implements EvictionPolicy {
private DoublyLinkedList keys;
private HashMap<String, Node> mapper;
private ReentrantLock lock;
public LRUEvictionPolicy() {
keys = new DoublyLinkedList();
mapper = new LinkedHashMap<>();
lock = new ReentrantLock(true);
}
@Override
public void keyAccessed(String key) {
lock.lock();
try {
// key is already present.
if (mapper.containsKey(key)) {
// access the node and move it to the front.
Node keyNode = mapper.get(key);
// delete the node.
keys.delete(keyNode);
// add to front.
keys.addFront(key);
} else {
// first time encountering this key.
Node front = keys.addFront(key);
mapper.put(key, front);
}
} catch (Exception ex) {
// do something here.
} finally {
lock.unlock();
}
}
@Override
public void keyEvicted(String key) {
lock.lock();
try {
if (mapper.containsKey(key)) {
Node keyNode = mapper.get(key);
keys.delete(keyNode);
mapper.remove(key);
}
} catch (Exception ex) {
// do something here.
} finally {
lock.unlock();
}
}
@Override
public String getKeyToEvict() {
if (keys.count() > 0) return keys.last().data;
return null;
}
}