简单老化缓存:我已经创建了一个简单的老化缓存,我已经让它通过了除了getExpired之外的所有单元测试。我试过在put之后和之前运行cleanExpiredRecords方法,真的不知道如何解决这个问题。如有任何建议将不胜感激。
package io.collective;
import java.time.Clock;
import java.util.HashMap;
import java.util.Map;
public class SimpleAgedCache {
private final Clock clock;
private final Map<Object, CacheEntry> cacheMap;
public SimpleAgedCache(Clock clock) {
this.clock = clock;
this.cacheMap = new HashMap<>();
}
public SimpleAgedCache() {
this(Clock.system(Clock.systemDefaultZone().getZone()));
}
public void put(Object key, Object value, int retentionInMillis) {
if (key != null && retentionInMillis > 0){
long expirationTime = clock.millis() + retentionInMillis;
cacheMap.put(key, new CacheEntry(value, expirationTime));
}
}
public boolean isEmpty() {
return cacheMap.isEmpty();
}
public int size() {
return cacheMap.size();
}
public Object get(Object key) {
cleanExpiredRecords();
CacheEntry entry = cacheMap.get(key);
if (entry != null){
return entry.value;
}
return null;
}
private void cleanExpiredRecords(){
long currentTime = clock.millis();
cacheMap.entrySet().removeIf(entry -> entry.getValue().isExpired(currentTime));
}
private static class CacheEntry{
Object value;
long expirationTime;
CacheEntry(Object value, long expirationTime){
this.value = value;
this.expirationTime = expirationTime;
}
boolean isExpired(long currentTime){
return currentTime >= expirationTime;
}
boolean isNotExpired(long currentTime){
return !isExpired(currentTime);
}
}
}
下面是它不断失败的Junit测试。我正在努力让我的代码通过单元测试。然而,当期望的答案是1时,它会继续返回2。预期:1实际:2
@Test
public void getExpired() {
TestClock clock = new TestClock();
SimpleAgedCache expired = new SimpleAgedCache(clock);
expired.put("aKey", "aValue", 2000);
expired.put("anotherKey", "anotherValue", 4000);
clock.offset(Duration.ofMillis(3000));
assertEquals(1, expired.size());
assertEquals("anotherValue", expired.get("anotherKey"));
}
2条答案
按热度按时间n3ipq98p1#
当客户端调用
get()
时会触发清理方法,但当它调用size()
时不会触发。换句话说,当调用size()
时,缓存实际上包含两个键->值对,并且只有在调用get()
时才删除过期的记录。这不应该失败:
smtd7mpg2#
我不认为两个看跌期权和大小期权之间的元素会被移除。