Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Object.finalize() do?

Tags:

java

object

finalize() is one of the 9 methods in java.lang.Object class. The api docs for the function state:

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

  • But what does the finalize() method actually do?
  • What happens if we manually call the finalize() method?
like image 914
Madeyedexter Avatar asked Nov 12 '22 19:11

Madeyedexter


1 Answers

it doesn't do anything by default but it gives you an interception point if you want to perform some action

this is the implementation of finalize() in java.lang.Object

  protected void finalize() throws Throwable { }

The general contract of finalize is that it is invoked if and when the JavaTM virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.


See Also

  • demo code (might not work in all cases)
  • When is the finalize() method called in Java?
like image 61
jmj Avatar answered Nov 15 '22 05:11

jmj