The traditional way to respond to garbage collection events is to register the WeakReference
s with a ReferenceQueue
, in which they'll automatically be enqueued when the referenced object is GC'd, and then to periodically poll the ReferenceQueue
(possibly in a separate thread) to do cleanups.
A standard trick is to extend the WeakReference
class, attaching any additional information you want to know when the cleanup occurs, and then to cast the WeakReference
objects in the ReferenceQueue
back to your MyWeakReference
to get the information.