您的位置:首页 > 其它

Lucene 4.0 BytesRefHash的一个bug

2017-09-01 22:16 369 查看
线上搜索忽然发现一堆死循环线程,最后全部卡在内存索引的BytesRefHashState的查找方法get上,而这个哈希表实现基本参考了lucene-core中的BytesRefHash方法。

这个再散列方法比较特别,inc = ((code >> 8) + code) | 1,code += inc,既不是线性探测也不是二次探测,哈希表的长度为2的幂,并且保证哈希表负载因子小于0.5。我理解这里不使用链表解决冲突是为了节约内存,不用二次探测和线性探测是为了避免聚集和二次聚集,但这同样带来了缓存不友好的问题,最重要的是是否会死循环?

模拟了一下,果然有死循环:

public static void main(String[] args) {
int code = 0;
HashMap<Integer, Integer> stepMap = new HashMap<Integer, Integer>();
int inc = 0, period = 0;
for (; ;) {
if ((period % 10000000) == 0) {
System.err.println("Period=" + period + ",Size=" + stepMap.size());
}
inc = (((code >> 8) + code) | 1);
code += inc;
if (!stepMap.containsKey(code)) {
stepMap.put(code, period);
++period;
} else {
int oldStep = stepMap.get(code);
System.err.println(String.format("Current period=%d, oldStep=%d, currentCode=%d", period, oldStep, code));
return;
}
}
}
输出:

Current period=72350, oldStep=23220, currentCode=1542835881

也就是hashCode为1542835881时,经过49130次哈希,就会回到原来位置,只要表长超过98260就会出现问题。

翻了一下最新的lucene 6.6.0版本,BytesRef实现已经变更:哈希方法改为murmurhash3,冲突解决方式改为线性探测。更好的哈希方法避免聚集,线性探测增加缓存友好。

具体改动为(Lucene-5604):https://issues.apache.org/jira/browse/LUCENE-5604
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: