I have a Class ref and array of Annotation refs, which together compose my Map key.Since I have no callback hooks for removing this key I need something similar as what WeakHashMap would do if my key was only that Class ref - removing the whole entry when Class ref is GCed.

Is there an easier way than rewriting the whole WeakHM (or some similar construct)?

So I take it the annotation refs point to annotations on the class ref?I could see a couple of options:

You could use a WeakIdentityHM using a Class ref as the key, and a nested normal HM using a key which has an array of weak annotation refs. This would then be wrapped in a delegate which emulates the composite key behavior.

Use a normal map, of any kind, and extend WeakReference to have an additional strong reference field, that points to your composite key class. Use this special reference for both the Class ref and all of the annotation refs. These are then registered in a ref queue, which is processed to remove gc'd entries periodically when accessing the map (by using the key reference). For this to work the key must do an identity check before comparing its contents (since the contents are gone during cleanup). If the map is concurrent you could do this cleanup in a separate thread.

Oh, but my class above is intended to be passed as a key to WeakHashMap. The ReferenceQueue polling will remove the only strong ref to the Key, at which point the WeakHashMap will do its normal thing and make the Key/value pair eligible for removal.

"bstansberry@jboss.com" wrote:Oh, but my class above is intended to be passed as a key to WeakHashMap. The ReferenceQueue polling will remove the only strong ref to the Key, at which point the WeakHashMap will do its normal thing and make the Key/value pair eligible for removal.

IMO it would be better to connect the logic to the map, then the entry is cleared in one pass, and you aren't tied to a particular map implementation.

"bstansberry@jboss.com" wrote:Oh, but my class above is intended to be passed as a key to WeakHashMap. The ReferenceQueue polling will remove the only strong ref to the Key, at which point the WeakHashMap will do its normal thing and make the Key/value pair eligible for removal.

Hmmm ... trying to put your code into real life showed some issues.

The way you do your refQueue is wrong. :-) And I don't see how you can do it right.

Since what you have to pass into WeakReference as Queue instance is the initial queue of actual type of your WeakReference - the type that's gonna be GCed - in our case the Class ref.