How finalize method works with phantom reference in java

868 Views Asked by At

Hi I have one doubt about phantom reference. What I understand the finalize method is called just before when object are going for garbage collection. But some time if object are not eligible for garbage collection then finalize method will not execute.

Now talking about phantom reference when this finalize method will called.

Is finalize always called in phantom reference.

I am very much confuse about this. Please help me.

3

There are 3 best solutions below

0
On

When object becomes available only through phantom reference then after the first GC finalize() method is invoked and after the second GC the reference is enqueued. If after that phantom reference is cleaned (or becomes unavailable itself) then the memory is cleared after the third GC.

0
On

Finalizers are never guaranteed to be called, whether there is a phantom reference or not. Don't rely on finalizers for any critical part of your code because there is no guarantee that they will be called in a timely manner or in fact at all.

Many people advocate that you simply should never use finalizers at all because they are incredibly difficult to use correctly.

1
On

Finalize will always be called, but not neccessarely, when you expect it. It may happen, that the call will only be made at the JVM shutdown (assuming you don't simply kill the program). You should not rely on finalize() in order to do significant work. But it is also good practice to implement a usefull finalize() and include a call to super.finalize() too.