Key cache generation

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

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

      

(Boolean parameter indicates whether the object should be added to the distributed or local cache)

My question is how should I create keys from value objects such as:

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

      

One approach is to provide hashCode () and equals () methods and use hashCode as the key. In that case, I wouldn't need the Person class to implement Serializable.

Alternatively, I could just use the Person object itself as the key. It looks like I still need to provide equals and hashCode methods, but I also need to implement Serializable. However, it would seem that there is less chance of collision using this approach because a Personality can only be equal to one instance of Person.

I am assuming that ehcache uses the equals () method of a key to determine if that key exists in the cache, is that correct?

Is any of the above approaches better than the other, or is there another approach that I have not considered?

Thanks Don

+2


source to share


1 answer


Your question about hashes is mostly orthogonal to the serializable question. In response to hashkey, I would use Apache Commons HashCodeBuilder. He does all the hard lifting for you. Similarly to Equal, use EqualsBuilder.

Remember that hash codes must remain unchanged over the life of an object, so only hashes are those internal elements that will not change.



I would not use the Person object as a key, as this will call its equals () to check key mappings, which is probably slower than comparing an integer hash code.

+1


source







All Articles