[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: finalize
- Subject: Re: finalize
- Date: Fri, 18 Aug 2006 13:26:54 -0600
Hi Bob:
Bob Simons wrote:
I had a bug in a new procedure I was writing (my fault, I admit),
wherein the close() method of many NetcdfFile objects was never called.
I dont understand why that would cause a NoClassDefFoundError ??
On Windows, this code ran fine. The Java implementation on Windows
(specifically the garbage collector) must have been smart enough to
recover all the memory allocated and close all the files when the
NetcdfFile objects were no longer referenced.
I don think it would do a file close on GC, but it would when the
application exits.
But on Linux, the procedure failed after many calls, and I got an
error message (from Java? from Tomcat? it doesn't matter) saying "too
many files open".
Fine. I fixed the problem in my code. But I two requests for you:
1) In the JavaDocs for the NetcdfFile class (up at the top), please
include the same suggestion as you already have in NetcdfFileCache's
JavaDocs regarding the use of "finally" to ensure that close() is
called. E.g.,
NetcdfFile ncfile = null;
try {
ncfile = NetcdfFile.open(fileName);
...
} finally {
ncfile.close();
}
good idea, i will add
2) I think it would be a huge improvement to NetcdfFile (and
presumably NetcdfFileCache, NetcdfDataset, NetcdfDatasetCache,
DODSNetcdfFile (which isn't in the latest copy of the documentation I
have), and any similar object), to include the following method (or
something like it):
protected void finalize() throws Throwable {
close();
}
As you probably know, the finalize() method is inherited from the
java.lang.Object class and is called whenever an object is eligible
for garbage collection. In this case, overriding finalize() lets you
ensure that the close() method always gets called.
In real life, it isn't always possible to use try/finally. That opens
up the possibility of not calling close() if an error occurs. It is
dangerous to have that resource leakage be a possibility.
Your use of finalize() prevents this type of resource leakage (as
dangerous as memory leaks in other languages) from occurring.
Ill have to think about this one. Standard java wisdom is to avoid the
use of finalize for these kinds of things. I think Josh Bloch's book
"effective java" has a section on that, though ill have to review it.
That book is more or less the accespted authority for these issues.
I admit again that it was my coding error that lead to these issue
coming up. But I think it is good defensive programming to have a
finalize() method for classes like these.
Thank you.
Sincerely,
Bob Simons
Satellite Data Product Manager
Environmental Research Division
NOAA Southwest Fisheries Science Center
1352 Lighthouse Ave
Pacific Grove, CA 93950-2079
(831)648-0272
address@hidden
<>< <>< <>< <>< <>< <>< <>< <>< <><