Max Lybbert
Posts: 314
Nickname: mlybbert
Registered: Apr, 2005
|
|
Re: Myths of Memory Management
|
Posted: Sep 8, 2005 11:53 AM
|
|
> finally blocks don't really have anything to do with GC, > so I'm not sure where you are going with this.
I have to say that my gripes w/ the finally clause are probably based on my C++ background.
In C++, "exception safe code" falls under various requirements. The basic guarantee is that if an exception is thrown, the programmer knows (a) data structures are left in a valid state, and (b) the algorithm doesn't leak resources (such as memory, but can include file locks, sockets [which come from a finite pool], disk files, etc.). The strong guarantee is that (a) the algorithm either completes successfully or has no effect, and (b) the basic guarantee also holds. The nothrow guarantee is that (a) no exception can be thrown, and (b) the strong guarantee holds.
In C++ you have to go through various acrobatics to avoid leaking resources. The basic heuristic is that you (a) allocate all resources through automatic variables (so that throwing an exception automatically calls the destructor), and (b) watch when you call functions/methods that can throw exceptions so that you know when things might get interupted, and order your calls accordingly. No, it's not fun, and yes, there's got to be a way to offload much of that to the computer. I've got a few ideas, but they're outside of the compiler (something like an exception checker, similar to Spin [http://www.cs.bell-labs.com/sys/doc/spin.html ], the thread-safe checker).
My point is that Java's implementation does NOT properly offload that work to the computer. In particular, the finally clause actually causes more tedious work than the C++ acrobatics. Simply put, the Java GC handles the leaking memory part, but since there's no way to know WHEN finalizers are called, you can't use them to handle the leaking of other resources (remember the lock example?). That must be done by hand, and must be done in a finally block. This means you end up typing the same clean up code in several finally blocks (and you must make sure those finally blocks are up to date), instead of once in the destructor.
> I see where you are going with the autopointers. However, > I prefer the delayed cleanup method.
To be honest, I'm a "whatever floats your boat" kinda guy. I've been looking into linking things to incremental garbage collectors (such as the Hans Boehm one included by default in GCC) for "litter collection" (i.e., to catch my mistakes). My main point is that I'm not all that find of finally blocks.
|
|