hash collision

61 views
Skip to first unread message

chench...@gmail.com

unread,
Feb 17, 2013, 3:39:11 AM2/17/13
to ehcache-sprin...@googlegroups.com
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.

David Karlsen

unread,
Feb 17, 2013, 5:31:38 AM2/17/13
to ehcache-sprin...@googlegroups.com
Maybe you could try switching to:
http://code.google.com/p/ehcache-spring-annotations/wiki/MessageDigestCacheKeyGenerator
?

2013/2/17 <chench...@gmail.com>:
> --
> You received this message because you are subscribed to the Google Groups
> "Ehcache Spring Annotations" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ehcache-spring-anno...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>



--
--
David J. M. Karlsen - http://www.linkedin.com/in/davidkarlsen

Eric Dalquist

unread,
Feb 17, 2013, 9:00:28 AM2/17/13
to ehcache-sprin...@googlegroups.com

That is the key generation style that the JSR-107 caching spec will use by default.

chenchun

unread,
Feb 17, 2013, 9:34:04 PM2/17/13
to ehcache-sprin...@googlegroups.com
Thanks, I'll try.

-- 
chenchun

在 星期日, 17 2月, 2013,10:00 PM,Eric Dalquist 写道:

ListCacheKeyGenerator

Reply all
Reply to author
Forward
0 new messages