As far as I know , in java if we want to manually call the garbage collector we can do System.gc().
1.What are the operations that we do inside our overriden finalize() method?
2.Is it required to override the finalize() method if we want to manually call the JVM garbage collector?
What are the operations that we do inside our overriden finalize() method?
Free memory alocated manually (through some native calls) i.e. not managed by GC. It is a really rare situation.
Some people put there also a check, that other resources connected with the object have already been released - but it's only for debugging purposes and it's not very reliable.
You must remember that:
finalize
is about memory and only memory.So never ever put there releasing any other resources (like file handles, locks). All those resources must be released manually.
And overriding finalize has nothing to do with calling System.gc()
.
Others already explained the finalize method.
Note however, that best practices is to design a "close"/ "clean-up"/ "termination" method to close/ clean-up the object and ask the developer to call this method explicitly. Finalizers should only be used as a safety net. (See "Item 7: Avoid finalizers" of "Effective Java" by Joshua Bloch)
Update:
In this case also consider to implement AutoCloseable to support try-with-resources blocks.
Overriding the finalize method is often done if you need to manually release resources (particularly those that would use large amounts of memory or cause locks, if they weren't released). For example, if you have an object that has a lock on a file or database table, you may want to override your finalize method in order to release those objects for use when your object is garbage collected.
As for whether or not overriding finalize is required, it absolutely is not. You can call System.gc() without ever overriding a finalize method. One word of caution, though - calling System.gc() doesn't absolutely dictate that the garbage collector will do anything. Consider it more of a "recommendation" to the JVM to run garbage collection, as opposed to a "mandate".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With