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.

Niru
  • 489
  • 6
  • 15

2 Answers2

4

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

Community
  • 1
  • 1
Marcinek
  • 2,144
  • 1
  • 19
  • 25
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.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142