Thursday, December 29, 2005

Reference Objects and hashcode

In my previous post, i had brought up the observation that Reference objects cannot be used as reliable keys in Maps/Sets. Intutively I had expected the Reference objects to delegate the equals/hashCode methods to its referrant object.But it was not so. It left me thinking why was it designed not to delegate.

The top reason that comes to my mind is that
if the referent object that the Reference points to is GC'ed, then if we are delegating, then equals/hashCode would have to be handled by Reference.Typically it would have do something like

public int hashCode(){
  if(get() == null) return 0 or -1;
  return get().hashCode();
}

This means that in a map, where keys are references, all the keys(references) whose referents
have been GC'ed, would end up having the same hashCode. This would cause weird runtime issues when the map is being resized and we would have no clue why ! Same hold true when we try to add ReferenceObjects to a Set.

We might also wonder why not then store the hashCode of the referent in a separate variable when creating the reference. Well hashCode can change over the lifetime of an object, meaning we will never know if the stored value is still valid. If it does not change, it will work.

Geez, i've been breaking my head trying to create something like a ConcurrentWeakHashMap and nothing seems to work. So I just made a call and decided my keys have to be objects whose hashCode will not change with data. Makes life more simpler. If at all I need a true ConcurrentWeakHashMap i've decided to use the less performant method of creating a WeakHashmap and doing a Collections.synchronizedMap() !

Subscribe to comments for this post

1 comment:

Derek DeMarco said...

Anything else of interest regarding the ConcurrentWeakHashMap? I have the same desire, and am hitting the same walls. I have a different approach that I'd be willing to discuss off thread, but its not perfect either. Anyway, hope you see this :) aim logicaldope

 
Clicky Web Analytics