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?

  • FYI : java.lang.Object.finalize() is deprecated in Java 9. May 13 '19 at 12:38

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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.