سؤال

I read an small article at some point about adding some callbacks to WeakReference objects that would be triggered upon garbage collection. Now, no mater how much I search, I cannot find it.

I need a way to execute some code whenever a weak referenced object is destroyed. I know that it can be done, I just don't remember how or whether I need a WeakReference or something else like a WeakHasMap?

هل كانت مفيدة؟

المحلول

Use ReferenceQueues to archieve that. You might want to look into PhantomReferences, too, depending on what you're actually trying to do (but WeakReferences 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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top