title: How to implement a canonicalizing mapping in Java?
body: <p>I am currently rolling my own little ORM, and find myself faced with the task of creating a canonicalizing mapping in order to prevent loading the same entity from the database more than once.</p>
  
  <p>My current approach is to use a <code>HashMap&lt;Object, WeakReference&lt;Object&gt;&gt;</code>. The key is the primary key of the mapped database-entity (an <code>ArrayList&lt;Object&gt;</code> if it is a composite key), and the values are <code>WeakReference&lt;Object&gt;</code>.</p>
  
  <p>My main problem is how to clean the map up? When an object is not used any more, the weak reference in the map will go <code>null</code>, and I will only discover this on the next lookup (or never, if I don't look the object up again). I could make the weak references register with a <code>ReferenceQueue</code> when they get cleared, and then check that queue every time I look something up. The cleared reference would not give me any hint as to which object was cleared though, so I guess I would have to subclass <code>WeakReference</code> to store the key in the map, so I can remove it after the reference was cleared.</p>
  
  <p>Is this the way to go, or is there any simpler way to implement this?</p>