Java Reference
In-Depth Information
it's donethere is no guarantee that your object holding the open file will
be collected before all the open file resources are used up.
Still, your objects that allocate external resources could provide a final-
ize method that cleans them up so that the class doesn't itself create
a resource leak. For example, a class that opens a file to do its work
should have some form of close method to close the file, enabling pro-
grammers using that class to explicitly manage the number-of-open-
files resource. The finalize method can then invoke close . Just don't rely
on this to prevent users of the class from having problems. They might
get lucky and have the finalizer executed before they run out of open
files, but that is riskyfinalization is a safety-net to be used as a last re-
sort, after the programmer has failed to release the resource manually.
If you were to write such a method, it might look like this:
public class ProcessFile {
private FileReader file;
public ProcessFile(String path) throws
FileNotFoundException
{
file = new FileReader(path);
}
// ...
public synchronized void close() throws IOException {
if (file != null) {
file.close();
file = null;
}
}
protected void finalize() throws Throwable {
try {
close();
} finally {
super.finalize();
}
 
Search WWH ::




Custom Search