gpt4 book ai didi

java - 相等的键触发缓存负载超过预期

转载 作者:行者123 更新时间:2023-12-02 03:33:27 25 4
gpt4 key购买 nike

也许我对cache2k的工作原理完全被误导了。我想缓存成本非常高的操作的结果,但即使使用相同的键,结果也总是会再次生成。首先我想,这些键并不真正相等,但即使 equals() 返回 true,缓存似乎也认为我想要新的结果。

import org.cache2k.Cache;
import org.cache2k.CacheBuilder;
import org.cache2k.integration.CacheLoader;
import org.junit.Test;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class MyCacheTest {

private static int count = 0;

Cache<MyCacheTest.MyKey, Integer> cache = (Cache) CacheBuilder.newCache(MyCacheTest.MyKey.class,
Integer.class)
.expiryDuration(1, TimeUnit.HOURS)
.loader(new CacheLoader<MyCacheTest.MyKey, Integer>() {
@Override
public Integer load(MyCacheTest.MyKey p) throws Exception {
return costlyOperation(p);
}
})
.build();

private Integer costlyOperation(MyKey p) {
count ++;
return 1;
}

public class MyKey {

Date date;

@Override
public boolean equals(Object o) {
return true;
}
}

// OK
@Test
public void testEquals() {
assertTrue(new MyKey().equals(new MyKey()));
}

// FAIL, somehow calls costlyOperation twice
@Test
public void testCostlyOperationCalledOnlyOnce() {
cache.get(new MyKey());
cache.get(new MyKey());
assertEquals(count, 1);
}
}

这很可能是我的误解,请有人解释为什么这不能按我的预期工作。

最佳答案

您实现了 equals,但没有实现 hashCode,并且此缓存实现使用 hashCode。添加:

@Override
public int hashCode() {
return 0;
}

to MyKey 给出了预期的行为。

(使用版本 0.26-BETA 进行测试)

关于java - 相等的键触发缓存负载超过预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37747392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com