我们遇到了一个奇怪的问题。我们获得了 Oracle Coherence 缓存的 KeySet,但无法直接从缓存中获取值,即使它没有更新活动。
以下代码始终失败(即输出“>>>>NULL”,因为未检索到对象)。问题是:为什么?
NamedCache nc = CacheFactory.getCache(cacheName);
Set<Object> keys = (Set<Object>)nc.keySet();
for ( Object key : keys ) {
Object o = nc.get(key);
if ( o == null ) {
System.out.println(">>>>NULL:"+keyStr);
}
}
缓存是具有多个索引的分区命名缓存。
关键是具有一个实例变量的对象(未显示),即 HashMap。
key 对象还具有 equals() 和 hashCode() 方法,如下所示:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((values == null) ? 0 : values.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
System.out.println("EQUALS");
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractCacheKey other = (AbstractCacheKey) obj;
if (values == null) {
if (other.values != null)
return false;
} else if (!values.equals(other.values))
return false;
return true;
}
我相信 Coherence 在此配置中使用序列化键对象的哈希,这将使这两种方法无关紧要,除非我不知道这对于前端缓存(本地 JVM,已关闭本地存储)和后端缓存(存储节点 JVM)。
我们的一些代码通过重建键、以标准顺序插入值来部分解决这个问题。这通常有效。我不明白为什么这是必要的,因为我们的 hashCode() 方法和 Java 的 hashCode() 用于 HashMap,AFAIK 对哈希的迭代顺序不敏感。为什么它通常但并不总是有效也是一个谜。