The finalize() method

You can think of Java's garbage collector as a death dealer. When it removes something from memory, it is gone. This so-called death dealer is not without compassion as it provides each method with their final last words. The objects give their last words through a finalize() method. If an object has a finalize() method, the garbage collector invokes it before the object is removed and the associated memory deallocated. The method takes no parameters and has a return type of void.

The finalize() method is only called once and there can be variability when it is run. Certainly, the method is invoked before it is removed, but when the garbage collector runs is dependent on the system. If, as an example, you have a relatively ...

Get Java 9: Building Robust Modular Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.