preface
recently, I saw the interview questions about redis when I visited the blog. It was mentioned that redis will use LRU and other elimination mechanisms when its memory reaches the maximum limit. Then I found some information about this to share with you. LRU is generally like this: the most recently used ones are put in the front, and the most recently unused ones are put in the back. If a new number comes and the memory is full at this time, the old number needs to be eliminated. In order to move data conveniently, you must use a data structure similar to linked list. In addition, to judge whether the data is the latest or the oldest, you should also use keys such as HashMap -Data structure in the form of value.
Implementation of the first method using HashMap
public class LRUCache {
int capacity;
Map<Integer,Integer> map;
public LRUCache(int capacity){
this.capacity = capacity;
map = new LinkedHashMap<>();
}
public int get(int key){
//If not found
if (!map.containsKey(key)){
return -1;
}
//refresh data if found
Integer value = map.remove(key);
map.put(key,value);
return value;
}
public void put(int key,int value){
if (map.containsKey(key)){
map.remove(key);
map.put(key,value);
return;
}
map.put(key,value);
//exceeds the capacity, delete the longest useless that is the first, or you can override the removeEldestEntry method
if (map.size() > capacity){
map.remove(map.entrySet().iterator().next().getKey());
}
}
public static void main(String[] args) {
LRUCache lruCache = new LRUCache(10);
for (int i = 0; i < 10; i++) {
lruCache.map.put(i,i);
System.out.println(lruCache.map.size());
}
System.out.println(lruCache.map);
lruCache.put(10,200);
System.out.println(lruCache.map);
}
The second implementation (double linked list + HashMap)
public class LRUCache {
private int capacity;
private Map<Integer,ListNode>map;
private ListNode head;
private ListNode tail;
public LRUCache2(int capacity){
this.capacity = capacity;
map = new HashMap<>();
head = new ListNode(-1,-1);
tail = new ListNode(-1,-1);
head.next = tail;
tail.pre = head;
}
public int get(int key){
if (!map.containsKey(key)){
return -1;
}
ListNode node = map.get(key);
node.pre.next = node.next;
node.next.pre = node.pre;
return node.val;
}
public void put(int key,int value){
if (get(key)!=-1){
map.get(key).val = value;
return;
}
ListNode node = new ListNode(key,value);
map.put(key,node);
moveToTail(node);
if (map.size() > capacity){
map.remove(head.next.key);
head.next = head.next.next;
head.next.pre = head;
}
}
//Move the node to the tail
private void moveToTail(ListNode node) {
node.pre = tail.pre;
tail.pre = node;
node.pre.next = node;
node.next = tail;
}
//Define bidirectional linked table nodes
private class ListNode{
int key;
int val;
ListNode pre;
ListNode next;
//Initializing a two-way linked table
public ListNode(int key,int val){
this.key = key;
this.val = val;
pre = null;
next = null;
}
}
}
like the first method, it will be easier to copy removeeldestentry. Here is a brief demonstration
public class LRUCache extends LinkedHashMap<Integer,Integer> {
private int capacity;
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
}
Read More:
- Implementation of retrial mechanism in Java
- [Solved] Redis Error: org.springframework.data.redis.RedisConnectionFailureExceptionjava.net.SocketTimeoutException
- Redis: DENIED Redis is running in protected mode [How to Solve]
- [Solved] java.lang.IllegalAccessError: class org.springframework.data.redis.core.$ Proxy237 cannot access its superinterface org.springframework.data.redis.core.RedisConnectionUtils$RedisConnectionProxy
- [Solved] Springboot uses redis to add LocaldateTime Java 8 error
- [Solved] Project Startup Error: Redis health check failed:Unable to connect to localhost6379
- [Solved] Project Startup Error: Redis health check failed: Unable to connect to localhost6379
- Failed to restart redis-server.service Unit not found [How to Solve]
- [Solved] Jedis connect and operate Redis error: Failed to create socket和connect timed out
- [Solved] Consider defining a bean of type ‘org.springframework.data.redis.core.RedisTemplate‘ in your configu
- Defining a bean of type ‘org.springframework.data.redis.core.RedisTemplate‘ in your configuration.
- JAVA 8: How to Convert List to Map
- [Solved] Redis Error: Error condition on socket for SYNC: No route to host
- How to convert a Java string into a number (stringtonumber)
- [Solved] Redis error: NOAUTH Authentication required.
- Redis Stand-alone Builds a Master-slave Copy Error [How to Solve]
- Springboot startup error: err config is disabled command (Redis Disables Config command)
- [Solved] Windows Redis Error: Could not create server TCP listening socket 127.0.0.1:6379: bind…
- How to Solve Flick operate Error: not serialized
- [Solved] Redis Error: Unexpected exception while processing command