Re:Newbie Memory Management
Posted: Thu Mar 02, 2006 1:25 am
There are no destructors in Java, but there are finalizers. Finalizers are fairly evil in that they complicate the implementation of the GC, slow things down, and ought to be unnecessary in the first place. When you create a local object in Java and its only reference goes out of scope, it is not destroyed immediately, but the next time the GC runs there is a good chance that object will be collected. If it has a finalizer, the GC will put it on a queue to be finalized later and it is not collected immediately.beyond infinity wrote:I don't know if java locally instantiated objects are destroyed per se if going outta scope - and if the destructors are called. If dependency lies in the order of how things are to happen, I'd say destroy() ere leaving the function.
IMO a sane design for a language with garbage collection would mix stack-based objects that have deterministically-invoked destructors with GC'd heap-based objects (that do not have finalizers, ever). That way you could still use C++'s RAII technique to dispose of non-memory resources in a timely and predictable fashion, while leaving pure memory reclamation up to the system. The closest thing I've seen so far is C#'s using block, but it's really just a hack. I think in C++/CLI it's possible to mix the GC and C++ destructor paradigms a lot more. Too bad it's even more complicated and decorated (Foo^ bar; anyone?) than plain old C++...