2

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.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
user711466
  • 109
  • 1
  • 3

3 Answers3

5

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.

Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
1

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.

Tema
  • 4,100
  • 2
  • 22
  • 12
0

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.

nfechner
  • 17,295
  • 7
  • 45
  • 64
  • 1
    The Javadoc for the (deprecated) System.runFinalizersOnExit says `By default, finalization on exit is disabled.` - so in fact, it is entirely possible to never finalize objects, if the runtime exits before they would be. And enabling it is deprecated because it's extremely unsafe. http://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#runFinalizersOnExit(boolean) – Steven Schlansker Apr 19 '11 at 07:43