Finalize:- It is a method present in a class which is called before any of its object is reclaimed by the garbage collector. Finalize() method is used for performing code clean-up before the object is reclaimed by the garbage collector.
Pankaja Shinde wrote:Finalize:- It is a method present in a class which is called before any of its object is reclaimed by the garbage collector. Finalize() method is used for performing code clean-up before the object is reclaimed by the garbage collector.
That says what it is/does, not when you might use it.
@Bhawana: Basically, Ulf's suggestion is the simplest. I have seen some books (fairly old now) suggest that one place that it could be useful is for releasing expensive resources held by an object (for example, a database connection) before it's finally cleaned up, but I have no idea whether that's still accepted practise or not.
The main thing to remember, if you ever do decide to write one: Don't assume (or rely on the fact) that it will EVER be run.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
The only case I can think of right now is when you're interfacing with a native library to perform some low level operations, usually in regards to file or network access. Since most of these low level operations already exist in the standard API, or in extensions, you will never really have cause to use finalizers yourself.
An example is FileInputStream. It requires native code to perform its duties, and overrides finalize() to close the stream and release file locks when it is garbage collected. This is only a very unreliable safety net for NEGLIGENT programmers who don't handle their streams properly.
posted 6 years ago
There are two legitimate uses.
One is to act as a "safety net" in case the owner of an object forgets to call its explicit termination method. While there's no guarantee that the finalizer will be invoked promptly, it may be better to free the resource late than never, in those (hopefully rare) cases when the client fails to call the explicit termination method.
A second legitimate use of finalizers concerns objects with native peers. A native peer is a native object to which a normal object delegates via native methods. Because a native peer is not a normal object, the garbage collector doesn't know about it and can't reclaim it when its Java peer is reclaimed. A finalizer is an appropriate vehicle for performing this task, assuming the native peer holds no critical resources
An actual example of using the finalize() method which I encountered in code supplied by one of our business partners (somewhat edited):
Based on the responses up to now in this threadyou should already realize that this is the worst possible use of the finalize method. I only post it as an example of what people mistakenly think is a good idea -- don't do this!