views:

264

answers:

1

Hi,

I'm using ehcache (via the Grails plugin). The method that adds objects to the cache requires the keys to be serializable, so a typical usage would be:

def key = 22
def someObject = new Object();
cacheService.cache(key, true, someObject)

(The boolean param indicates whether the object should be added to a distributed or local cache)

My question is how I should go about generating keys from value objects such as:

class Person implements Serializable {
  String firstName
  String lastName
  Integer age
}

One approach would be to provide a hashCode() and equals() methods and use the hashCode as the key. In this case, I wouldn't need to make the Person class implement Serializable.

Alternatively, I could simply use the Person object itself as the key. It seems like I would still need to provide the equals and hashCode methods but would also need to implement Serializable. However, there would seem to be a smaller chance of collisions using this approach because a Person can only be equal to another instance of Person.

I'm assuming that ehcache uses the equals() method of a key to determine whether that key already exists in the cache, is this assumption correct?

Is either of the approaches outlined above intrinsically better than the other, or is there another approach that I haven't considered?

Thanks, Don

+1  A: 

Your hashkey question is mostly orthogonal to the serializable question. In answer to the hashkey, I'd use the Apache Commons HashCodeBuilder. It does all of the heavy lifting for you. Similarly with equals, use the EqualsBuilder.

Remember though, hashcodes need to stay the same over the lifespan of the object, so only hash those internal elements that won't change.

I'd avoid using the Person object as the key as that'll call it's equals() to check key comparisons, which is likely slower than comparing an integer hashcode.

Chris Kessel
But there's also less chance of collisions if I use Person, because that can only be equal to other instances of Person
Don
One, worrying about that collision is pr-eoptimization. Remember the optimization rules :). 1) Don't optimize, 2) Don't optimize yet. Second, the likelihood of two person objectcreating the same hash are pretty small. Three, if you're going to use Person as your key then you have to implement equals() hashcode() anyway UNLESS you're relying on actual object equality (==) for lookup rather than equivalance (equals()).
Chris Kessel