Java – Explicit call to finalize() method in Java

garbage-collectionjava

I was reading about finalize() method that it may be invoked automatically when an object is eligible for garbage collection.Now this uncertain.But what happens if we call it explicitly.Does it necessarily do a cleanup or is it just a normal Java call?

Best Answer

A finalize() method is a method like any other. It does whatever you program it to do. The only thing special is that it may be called unpredictably by the JVM before an object is garbage collected. If you call it manually, it does the same thing it would do during a GC-triggered call.

However, with all modern garbage collectors, in practice you cannot rely on an object being collected at any particular time, or in fact at all. Therefore you cannot use finalize() to ensure that some action will be performed, which severely limits is usefulness. (About the only thing it is good for is debugging when objects get collected, and the JVM has better options for that.) This is why the general advice is "Just ignore finalize() altogether".