You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.2 KiB
97 lines
2.2 KiB
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
public class Cache<K, V> {
|
|
private Map<K, CacheEntry> cacheMap;
|
|
|
|
public Cache() {
|
|
cacheMap = new HashMap<>();
|
|
}
|
|
|
|
public void put(K key, V value) {
|
|
cacheMap.put(key, new CacheEntry(value));
|
|
}
|
|
|
|
public void put(K key, V value, long expireTimeMs) {
|
|
cacheMap.put(key, new CacheEntry(value, expireTimeMs));
|
|
}
|
|
|
|
public V get(K key) {
|
|
CacheEntry entry = cacheMap.get(key);
|
|
if (entry == null) {
|
|
return null;
|
|
}
|
|
if (entry.isExpired()) {
|
|
cacheMap.remove(key);
|
|
return null;
|
|
}
|
|
entry.updateAccessTime();
|
|
return entry.getValue();
|
|
}
|
|
|
|
public boolean containsKey(K key) {
|
|
CacheEntry entry = cacheMap.get(key);
|
|
if (entry == null) {
|
|
return false;
|
|
}
|
|
if (entry.isExpired()) {
|
|
cacheMap.remove(key);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public V remove(K key) {
|
|
CacheEntry entry = cacheMap.remove(key);
|
|
return entry != null ? entry.getValue() : null;
|
|
}
|
|
|
|
public int size() {
|
|
return cacheMap.size();
|
|
}
|
|
|
|
public void clear() {
|
|
cacheMap.clear();
|
|
}
|
|
|
|
private class CacheEntry {
|
|
private V value;
|
|
private long createTime;
|
|
private long accessTime;
|
|
private long expireTimeMs;
|
|
|
|
public CacheEntry(V value) {
|
|
this(value, -1);
|
|
}
|
|
|
|
public CacheEntry(V value, long expireTimeMs) {
|
|
this.value = value;
|
|
this.expireTimeMs = expireTimeMs;
|
|
this.createTime = System.currentTimeMillis();
|
|
this.accessTime = this.createTime;
|
|
}
|
|
|
|
public V getValue() {
|
|
return value;
|
|
}
|
|
|
|
public void updateAccessTime() {
|
|
this.accessTime = System.currentTimeMillis();
|
|
}
|
|
|
|
public boolean isExpired() {
|
|
if (expireTimeMs <= 0) {
|
|
return false;
|
|
}
|
|
return System.currentTimeMillis() > createTime + expireTimeMs;
|
|
}
|
|
|
|
public long getCreateTime() {
|
|
return createTime;
|
|
}
|
|
|
|
public long getAccessTime() {
|
|
return accessTime;
|
|
}
|
|
}
|
|
}
|