This may not be the answer you are looking for, but do you think you are using PhantomReference instead of overriding finalize() ? Here is an article that talks about this.
The basic idea is that it is not recommended to rely on the finalyze() method for preprocessing, since
- You cannot predict when it will be called.
- It uses JVM resources.
- This may interfere with garbage collection.
PhantomReference provides a cleaner way to trigger an action when a garbage collector deletes an object.
Object objectToHandle = new Object(); ReferenceQueue queue = new ReferenceQueue(); PhantomReference reference = new PhantomReference(objectToHandle, queue);
When an objectToHandle is deleted from memory by the garbage collector, its reference will be added to the queue . You can detect this by calling queue.remove() and then do your cleanup.
Note: PhantomReference.get() always returns null , so it is not possible to return an object after it has already been deleted from memory.
noscreenname
source share