Wait for garbage collection of a specific object

I just delved into the commons-io library and found this:

Keeps track of files awaiting deletion, and deletes them when
an associated marker object is reclaimed by the garbage collector.

This can be found in the documentation for the object FileCleaningTracker.

Now I'm just wondering how can I do this myself? How does my code detect when an object is regenerated by the garbage collector?

+5
source share
2 answers

According to the source code , it uses a PhantomReference . According to the documentation:

Phantom , , , . Phantom , Java.

, phantom phantom, - .

, , phantom : get phantom null.

, phantom , . , phantom, , .

PhantomReference :

referent - , phantom

q - , , null,

q ReferenceQueue. PhantomReference ReferenceQueue, referent phantom . , PhantomReference poll() remove() ReferenceQueue.

:

T objectToWatch = ...;
ReferenceQueue<T> referenceQueue = new ReferenceQueue<T>();
new PhantomReference<T>(objectToWatch, referenceQueue);

// Later on, probably in another thread...
Reference<? extends T> nextReference = referenceQueue.remove();
// Tidy up!

: PhantomReference sibling SoftReference WeakReference, . java.lang.ref.

+9

, , finalize() , .

: , , - .

+1

All Articles