在caffeine中的lfu通过一个long array来记录各个数据的被访问次数,每个被访问到的元素都将被通过4次不同的hash seed来计算位置,分别记录四次,以便达到最小的hash冲突可能性。
因此,long array的每个槽位中的64位空间,出于频度记录需要与空间的平衡,64位被分为4个16位的空间,而16位的空间又将都将被分为4个4位空间区域分别记录4个hash seed的结果。
static final long[] SEED = new long[] {
0xc3a5c85c97cb3127L, 0xb492b66fbe98f273L, 0x9ae16a3b2f90404fL, 0xcbf29ce484222325L};
四次的hash seed是几种知名hash算法的混合,包含fnv-1a,cityhash,murmur3.
当一个元素被访问的时候,将尝试通过increment()方法,增加一次访问次数。
public void increment(@Nonnull E e) {
if (isNotInitialized()) {
return;
}
int hash = spread(e.hashCode());
int start = (hash & 3) << 2;
// Loop unrolling improves throughput by 5m ops/s
int index0 = indexOf(hash, 0);
int index1 = indexOf(hash, 1);
int index2 = indexOf(hash, 2);
int index3 = indexOf(hash, 3);
boolean added = incrementAt(index0, start);
added |= incrementAt(index1, start + 1);
added |= incrementAt(index2, start + 2);
added |= incrementAt(index3, start + 3);
if (added && (++size == sampleSize)) {
reset();
}
}
以上是increment()方法的全貌。首先,在通过spread()方法增强了原生hash方法返回的hash code之后,将会通过与3相与的结果,定位其结果具体的存在位置(结果为0到3)并左移2位。
之后,通过indexOf()方法,分别根据上述的4个hash seed,定位到long array上的具体的位置。
int indexOf(int item, int i) {
long hash = SEED[i] * item;
hash += hash >> 32;
return ((int) hash) & tableMask;
}
在确认到具体的long槽位上之后,继续通过incrementAt()方法定位到long槽位上的具体位置上。
boolean incrementAt(int i, int j) {
int offset = j << 2;
long mask = (0xfL << offset);
if ((table[i] & mask) != mask) {
table[i] += (1L << offset);
return true;
}
return false;
}
前文提到,在该方案下的最小空间是一段4位的空间,那么可以想到,4位空间可以得到的最大大小是15,因此在此处的代码也可以看到,当所要存放的空间大于15的时候就不会再增加,否则,就在原先空间的基础上增加1。
由此,可以举个例子,以大小32的long array为例子,某个key得到的hash code可能在4个seed的下分别落在long array的四个位置,举例,四个seed的结果分别落在1,2,3,4上,之后将hash code与3相与,得到一个不大于3的位置,假设这个位置为1,那么第一个hash seed的结果将会存放在long array上的1槽位的16位上,第二个结果将会存放到2槽位的20位上,第三个结果将会存放到3槽位的24位上,第二个结果将会存放到4槽位的28位上。这样,能够尽可能的保证hash冲突的概率到最低。
(如果四个位置都已经被填满到15,会将整体数组中的频数减半)
那么如何在需要得到指定key的被访问次数的时候在这个long array上获取呢。
public int frequency(@Nonnull E e) {
if (isNotInitialized()) {
return 0;
}
int hash = spread(e.hashCode());
int start = (hash & 3) << 2;
int frequency = Integer.MAX_VALUE;
for (int i = 0; i < 4; i++) {
int index = indexOf(hash, i);
int count = (int) ((table[index] >>> ((start + i) << 2)) & 0xfL);
frequency = Math.min(frequency, count);
}
return frequency;
}
定位方式还是和前文一样,但是最终返回的结果则是四个seed结果的最小值,这样,当其中一个hash seed冲突后,能够保证不会影响到最后的结果。