Reputation: 5097
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?
Upvotes: 8
Views: 524
Reputation: 17441
Your confusion seems to be whether there is a memory leak or not. You are trying to establish this by looking at whether finalize()
was called or not. If that is so then it's the not the correct to check whether there is a memory leak or not.
Just so we're clear, in Java, memory leaks mostly mean hidden references to objects you don't need.
Purpose of finalize()
to give an opportunity to developer to clean up his own mess (connections, streams, ...). Memory is supposed to be JVM's mess/headache and cleaned up by GC.
So in short, fact that "GC guarantees to call finalize()
before is frees memory", shouldn't be interpreted as "if finalize()
is not called there is a memory leak". It could simply be that that object is not yet garbage collected.
If you're looking to find memory leak use a tool. See options:
Upvotes: 0
Reputation: 2759
According to all I read on Java basics you should never rely on finalize to be run. finalize() is not a destructor you may know from other languages.
From java.lang.Object javadoc:
The Java programming language does not guarantee which thread will invoke the finalize method for any given object.
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#finalize()
The way I see things, the dreaded finalize should and is only used if you include some native code in your app. But even then be sure not to rely on it.
Upvotes: 1
Reputation: 115328
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.
Upvotes: 4
Reputation: 9058
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.
Upvotes: 2