We don\'t have any destructor in Java as we have in C++.
Q1. How should we clean up any Object in java.
Q2. Is there any a
You generally cannot "clean up" Java objects yourself. The garbage collector decides when to clean objects up. You can indicate when you are done with an object reference by setting it to null
, but generally just letting it go out of scope is good enough. Either way, you still have no control over when it gets garbage collected.
The finally
block is intended for performing actions whether an exception is thrown from a try
block or not, and is the best place to perform clean up. Generally you only would clean up non-object resources like open streams.
finalize()
is not guaranteed to be called because the garbage collector is not guaranteed to be called before your program exits. It is not really like a C++ destructor because C++ destructors are always called and you can rely on them being called. You cannot rely on finalize()
being called.
So 1) use finally
blocks to release non-object resources 2) let the garbage collector clean up object-resources 3) you can hint to the garbage collector that you are done with an object by setting it to null
if it is used in a long-running method.
Here's a good insight about finalizers.
The finalize is used similar to a destructor, but, if you use the try...finally block for resources then you can open a resource and in the finally block you close the resource.
The finally block is always called, when the block is exited, either normally or through an exception being thrown.
Finalize is risky for resource management, as you don't know when it will be called, and if it closes an object that also has finalize then it can take a while.
The finally block is the better approach.