5

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.

0

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.