I'm implementing LRU cache in Java using my own implementation of DoublyLinkedList with a node having integer key and values where the key denotes the page identifier and the value denotes its location on the disk. Also, I am using a Hashmap for O(1) access. I know the following basics of implementation:
If requested key is a cache hit, then return its value(i.e. its location) and move this node to the front of the DoublyLinkedList.
I have a doubt in the other important aspect when it's a miss. According to various resources, when it's a miss then the page number that is the key in my case is set to head of the LinkedList and while doing that, if we encounter the capacity to be full then we delete the element at the end and then enter it to the front. Now for the purpose of implementation, what should be the 'value' of such page number (i.e. the key) when I bring it into the cache? Should I set it to garbage? In my below presented implementation of 'get' method, I am returning -1 currently upon a miss.
Also, in practical production code of LRU cache, does the cache contain the page numbers or actual values stored at those page numbers? T
Please help me clear this aspect. Thanks.
import java.util.HashMap;
public class LRU {
private static class Node {
Node previous;
Node next;
int key;
int value;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
Node head = null;
Node tail = null;
HashMap<Integer, Node> hmap = new HashMap<>();
public int get(int key) {
if (hmap.containsKey(key)) {
Node n = hmap.get(key);
remove(n);
moveToFront(n);
return n.value;
}
return -1;
}
public void remove(Node n) {
// if n is head
if (n.previous == null) {
head = head.next;
} else {
n.previous.next = n.next;
}
//if n is tail
if (n.next == null) {
tail = n.previous;
} else {
n.next.previous = n.previous;
}
}
public void moveToFront(Node n) {
if(n==head)
return;
if(n.next==null)
{
n.previous.next=n.next;
tail = n.previous;
n.previous = null;
n.next = head;
head = n;
}
else {
n.previous.next=n.next;
n.next.previous=n.previous;
}
}
public void set(int key, int value) {
}
}
LinkedHashMapinstead of rolling out your own code. Besides that, it doesn’t make any sense to insert nodes denoting non-existing entries. At this point, you only have described a kind of map, without telling what “page numbers” or “actual values stored at those page numbers” means. So don’t ask questions about it, you are the one who decided that a cache is needed for this data. - HolgerLinkedHashMap, using this constructor withtrue, so hits move entries to the front and overrideremoveEldestEntrywhose documentation already shows how to do fixed size. - Holger