This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I suspect finalize() is there because it is there in C++. It is intended for "cleaning up" resources when an object is deleted by the garbage collector. It is probably only worthwhile using it when there is "native" code; any Java resources like FileReaders should be closed in the method which uses them.
If you are not using native code, you will hardly ever use finalize(), except for the one good reason for using anything: "I wanted to see what happens if . . ."
I think there is a mistake in the finalize method on the website you quoted, Raghavan Muthu. They create the file reading object in one method, then close and set it to null in finalize(). That is a mistake; until finalize() is called, the file is unavailable to other objects.
Originally posted by Campbell Ritchie: I think there is a mistake in the finalize method on the website you quoted, Raghavan Muthu. They create the file reading object in one method, then close and set it to null in finalize(). That is a mistake; until finalize() is called, the file is unavailable to other objects.
I don't see any mistake there Campbell. If i am right, you are talking about the article which speaks about "Writing a finalize() method". Right?
It opens a file in the *constructor* and closes and set the reference to null in the finalize() method. what is wrong in it?
As far as I remember, one of the examples on a website quoted earlier had a FileReader and BufferedReader instantiated in a method, and closed in the finalize() method. This is almost certainly a mistake because:
There is no guarantee that finalize() will be called at a particular time.
There is no guarantee that finalize() will be called at all. In which case the file remains locked by the Readers.
Even if finalize() is called, there may be a delay of seconds or minutes when the Readers remain open and the file is locked.
The correct way to handle FileReaders is to declare them as local variables, and use a finally block to close them:Obviously there are different ways to handle the Exceptions, but this method ensures that the Readers are only open as long as they are needed, and are definitely closed as soon as they are finished with.
This example also shows how unnecessary the finalize() method is in normal programming.
Joined: Oct 13, 2005
. . . and instantiating a FileReader in a constructor is even worse.
Originally posted by Campbell Ritchie: It might be an example of the sort of thing you can put in finalize() but it actually serves to emphasise how little one actually uses finalize(). You were unlucky picking that particular website.