Java – finalized has 2.5 gigabytes of memory in 4 gigabytes

I have read many articles about how finalizers work. Here is my understanding: if a class has implemented the finalize method, the JVM will create a finalizer instance on the object as a watchdog

When GC runs, it marks the objects to be disposed and adds them to the reference queue, and then the finalizer thread selects these objects from the queue and executes their finalization methods

My question is: how to find the object from the heap dump, whose termination method is not completed for some reason and starts to accumulate the reference queue?

Are reference queues arranged in a specific order?

Solution

This may not be the answer you are looking for, but have you considered using phantom reference instead of overriding finalize()? This is an article that discusses it

The basic idea is that relying on the finalyze () method for pre cleaning is not recommended because

>You cannot predict when you will be called. > It takes up the resources of the JVM. > It prevents objects from being garbage collected

Phantom reference provides a more concise way to trigger the garbage collector to remove objects

Object objectToHandle = new Object();
ReferenceQueue queue = new ReferenceQueue();
PhantomReference reference = new PhantomReference(objectToHandle,queue);

When the garbage collector deletes objecttohandle from memory, its reference is added to the queue You can call queue Remove () to detect this, and then perform a cleanup operation

// will block until a reference becomes available
Reference removedRef = queue.remove();
//.. you can Now perform clean-up actions

Note: phantom reference Get() always returns null, so you cannot recover an object after it is deleted from memory

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>