4 ms·
> If there was an additional type of weak-like reference, that had a callback with an object before it was garbage collected, this conundrum would be simple. Y
by MaulingMonkey 13y ago
> If there was an additional type of weak-like reference, that had a callback with an object before it was garbage collected, this conundrum would be simple.
You've basically described weak references to objects with finalizers. Unfortunately, I'd wager this is even more expensive, not less.
- twic 13y agoNo, TheLoneWolfling's idea can't be implemented with weak references with finalizers. Firstly, finalizers only run after weak references are cleared (i think - please correct me if i'm wrong!). Secondly, he needs GC to trigger code that mutates the no-longer-referring object; the finalizer runs in the no-longer-referred-to object. He's right that a new VM-level hook would be required to implement his idea. The benefits don't clearly justify making a change of that magnitude.
- MaulingMonkey 13y agoDepends. I'm imagining e.g. your large parent string invasively giving it's sub-slices copies on finalization through it's own list, in which case the weak references clearing isn't much of an issue. Not easy to make fast and thread safe however. In C#, WeakReference can take a boolean parameter during construction to specify if it tracks post-finalize or not (defaulting to the same behavior as Java which google tells me is as you say: not), and you can re-register your finalizer, but even so this kind of thing isn't what the GC is primarily designed for and it will probably show. I'm not sure if you can re-register finalizers in Java.
- ajanuary 13y agoFinalisers run before weak references are cleared. You do, however, have the GC cost of having a finalized.