Hi Lee,
I am curious about the comment "
Any Ideas, should i be using a weakHashMap? (possibly not as no one has mentioned that!)" What hasn't been mentioned? Doing a search for WeakHashMap in this forum returns 70 matches, and there are 20 matches for WeakReference.
There is also a really great post by
Phil Maquet where he takes the kind of comments I make below, and creates a viable solution from it. Along the way he discards the WeakHashMap as he felt the WeakReference was in the wrong place (the key - he wanted it to be the value) so he created his own collection. Perhaps searching for his member number with either of the keywords might bring it up.
There are several things you need to be aware of:
Make sure your key is something that is unique to your client, and will therefore disappear when your client disapears. Remember that the WeakReference will only be cleared if there are no more strong references to the key. A common mistake is to use the one and only remote object that you exported as the key - however this will always have a strong reference (held by the RMI registry) so it will never be removed from a WeakHashMap (and Unreferenced will never be called (for those who implement that interface)).
Make sure you wait long enough for the distributed garbage collector (DGC) to run. As this is (presumably) an RMI solution, a distributed garbage collector will run roughly every 20 minutes. You can change the lease value to reduce the time before the DGC notices that there are no more strong references (i would recommend against permanently setting this - just set it from the command line for
testing, and note it in your documentation), or you could have a separate
thread requesting that garbage collection run more often (see next point).
Have some other thread running that will wake waiting threads if the DGC removes a key-value pair from the collection. Just having the key-value pair removed from the collection is only half the solution, and it has a potential problem: waiting clients have not been notified that the lock has been removed. How can they? They are waiting for some thread to call notify (or notifyAll), and the WeakHashMap does not know to do this.
So you are going to need a separate thread (possibly a daemon thread) that will watch the WeakHashMap and call notifyAll if a record has been removed from it. You might want an accessible counter that monitors how many records have been explicitly locked and compare that to how many records are in the WeakHashMap, and perform suitable actions if they differ.
Hopefully this has given you some ideas.
Regards, Andrew