Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you count on .finalize() to be called?

I was attempting to instrument some of my Java code to ensure objects were being garbage collected correctly, and I found that surprisingly it wasn't being called as often as I expected.

I am now wondering if this is because of faulty instrumentation or an actual memory leak I need to solve. the VisualVM profiler seems to indicate the former.

The situation of concern is that I have a thread which handles requests and inside the request creates thousands of temporary objects. Sometimes, the socket this thread writes to is unexpectedly closed and the thread hits an exception and dies.

When the Thread dies, it doesn't seem like .finalize() is ever called on those objects. Is this a reason to not trust my instrumentation?

like image 706
Kevin Dolan Avatar asked Oct 24 '11 17:10

Kevin Dolan


2 Answers

Finalize() is not the solution. You cannot know when finalizer will be called if any. If your problem is exception use try/catch/finally blocks and close/clean all stuff you want to close in finally block. This guarantees that everything will be cleaned in both cases: the logic terminated normally or exception was thrown.

like image 128
AlexR Avatar answered Oct 18 '22 23:10

AlexR


No. There is no guarantee that it will be called. However, it is usually called. It may be that you are not properly releasing your objects, or the garbage collector has not run, or the finalizer thread is waiting for a good time to run.

You can read about it in the Finalization of Class Instances portion of the language spec.

like image 26
Clint Avatar answered Oct 18 '22 21:10

Clint