What if the finalizer makes the object available?

In Java, finalize is called on an object (which overrides it) when it is about to collect garbage, so when it is not available. But what if the finalizer makes the object available again, what happens next?

+6
java garbage-collection memory-management jvm finalizer
source share
5 answers

The object will not be assembled until it is again inaccessible.

According to JavaDoc , finalize () will no longer be called.

+9
source share

Then the object does not receive the garbage collected mainly. This is called resurrecting an object. Search for this term and you should get a bunch of interesting articles. As Jim noted, the important point is that the finalizer will only run once.

+10
source share

If you carefully read the description of the API, you will see that the finalizer can again make the object available. An object will not be dropped until it is inaccessible (again), but finalize() will not be called more than once.

+7
source share

Yes, that’s why you don’t use finalizers (well, one of many reasons).

There is a reference collection that is designed for this. I will review it and publish it here in a second, but I think it is a PhantomReference.

Yep, PhantomReference :

Phantom reference objects that are queued after the collector determines that their referents can be returned. Phantom links are most often used to plan attacks to prevent tampering in a more flexible way than is possible with the Java finalization mechanism.

+3
source share

Actually, another pass is performed to check and make sure that there are no more references to the object. Since he will not pass this test in his second pass, you will not end up freeing up memory for the object.

Since finalize is called only one time for any given object, the next time it has no references, it will simply free up memory without causing completion. Some good info here is on completion.

+3
source share

All Articles