public class HashCollisionTest {
private int countA;
public void setCountA(int countA) {
this.countA = countA;
}
@Cacheable(cacheName = "LRUCache-1d")
public int sum(Integer a, Integer b) {
countA++;
return a + b;
}
public int getCount() {
return countA;
}
}
public class Cacheable2Test {
@Autowired
private HashCollisionTest hashCollisionTest;
@Test
public void test() {
Integer _108 = 108, _109 = 109, _34 = 34, _3 = 3;
//test passed
Assert.assertEquals(hashCollisionTest.sum(_108, _34), hashCollisionTest.sum(_109, _3));
}
Hi,
I met a hash collision problem with the code above. I use the default CacheKeyGenerator "HashCodeCacheKeyGenerator". I checked the source code and found the code below that cause the hash collision. Since 108*31+34=109*31+3, so the unit test passed. Is there a method to fix the problem or I have to write a custom CacheKeyGenerator?
HashCodeCacheKeyGenerator:
protected void append(LongGenerator generator, int[] a) {
for (final int element : a) {
generator.hash = MULTIPLIER * generator.hash + element;
}
}
@Override
protected void appendHash(LongGenerator generator, Object e) {
if (e instanceof Double) {
generator.hash = MULTIPLIER * generator.hash + Double.doubleToLongBits(((Double)e).doubleValue());
}
else if (e instanceof Long) {
generator.hash = MULTIPLIER * generator.hash + ((Long)e).longValue();
}
else {
generator.hash = MULTIPLIER * generator.hash + e.hashCode();
}
}
regards,
Chun Chen.