문제

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