Is there a way to know before an java object get destroyed??
For example:
class A{}
I have instantiated it as new A(). Now I would like to know when this object will get destroyed and do some operations before it get destroyed.
Your intention is highly unrecommended. Since it is entirely unpredictable when the gc is running and when this method is actually called.
How ever:
You can override the finalize()
method of Object
:
For Details see here: When is the finalize() method called in Java?
This method is called if and when the gc determines that a particular object is not referenced any more.
See also: Oracle JavaDoc for Object
Yes, there is a way, it is called "object finalization". Look at the Object.finalize()
method. But beware: if that path down you go, only pain will you find.