Use ReferenceQueue
s to archieve that. You might want to look into PhantomReference
s, too, depending on what you're actually trying to do (but WeakReference
s work with the queues, too). Just create a reference queue and pass it as a second argument to the reference-constructor. When the GC remove the object, the reference is enqueued and you can get it using remove()
(blocking) or poll()
(non-blocking) on your queue.
There is an alternative: implementing finalize
. It'S much less flexible though and runs in another thread, too (so you still have concurrency - with the addition of not even knowing which thread will execute it). The ReferenceQueue is superiour in all aspects.