底层维护了一个队列,越先进队列的,越先被淘汰
package com.darwin.redis.eliminated;
import java.util.HashMap;
import java.util.Map;
/**
* FIFO Java代码实现
* @author yanghang
*/
public class FIFOUtil {
/**
* 用来快速定位节点位置
*/
private final Map<String, Node> map;
/**
* 缓存大小
*/
private int size;
/**
* 虚拟头尾节点
*/
Node head;
Node tail;
/**
* 缓存大小
*/
int capacity;
public FIFOUtil(int capacity) {
head = new Node("", null);
tail = new Node("", null);
head.next = tail;
tail.pre = head;
size = 0;
this.capacity = capacity;
map = new HashMap<>();
}
/**
* 添加元素进入缓存
*
* @param key 键
* @param value 值
*/
public void put(String key, Object value) {
Node node = new Node(key, value);
node.pre = tail.pre;
node.pre.next = node;
node.next = tail;
tail.pre = node;
map.put(key, node);
if (size < capacity) {
size++;
} else {
// 删除队首
Node next = head.next;
head.next = next.next;
head = head.next.pre;
map.remove(next.key);
}
}
/**
* 获取缓存的值
*
* @param key 键
* @return 缓存键对应的值
*/
public Object get(String key) {
if (map.containsKey(key)) {
return map.get(key).val;
}
return null;
}
/**
* 内置双向链表
*/
static class Node {
String key;
Object val;
public Node(String key, Object val) {
this.key = key;
this.val = val;
}
Node pre;
Node next;
}
public static void main(String[] args) {
FIFOUtil FIFOUtil = new FIFOUtil(10);
for (int i = 0; i < 100; i++) {
FIFOUtil.put(i + "", i);
}
for (int i = 90; i < 100; i++) {
System.out.println(FIFOUtil.get(i + ""));
}
}
}