What Is Finalize in Java?
- Garbage collection is one of the more advanced topics in Java programming. Strictly speaking, Java developers can go entire careers without ever needing to know much about the garbage collector and how it functions. Essentially, each object created in a Java program is registered with the Java runtime, along with a count of all the places there's an existing reference to that object. When an object is no longer referred to by any other objects, the system marks it for collection, and the next time the garbage collector runs, it deletes that object.
- Things are different in other programming languages, such as C++, for example. In C++, the developer controls when an object is removed from memory, as opposed to the system. This is known as "deterministic memory management," and it has both its pros and cons. The primary plus side to this is that the developer knows exactly when in the code the object is deleted. However, it's extremely easy to delete an object that may still be in use elsewhere in the code.
- In C++, developers can add a destructor to a class, which is a method that is called whenever an object is deleted. This allows the developer to execute code when the object is no longer needed, perhaps to delete its children or to clean up resources. In Java, the system provides the finalize method, which developers can override to provide similar functionality. The primary difference is that the finalize method is called whenever the runtime determines that the object has no further references and can be collected.
- While finalize can provide functionality similar to C++'s destructor, it should really be used with care. Generally speaking, while overriding the finalize method can be perfectly fine for most situations, you shouldn't rely on it for ensuring resources are cleaned up at a particular time. For example, if you have a database connection open in an object that's closed in finalize, you can still potentially create too many connections to the database and pass the database's limit before the garbage collector has finalized all of the objects -- even if you no longer have references to them anywhere.