2 ms·
From the article: public type1 getFrame() { type2 child = this.getChild(); type3 var = this.something(); // `this` may now be garbage col
by btown 12y ago
From the article:
public type1 getFrame() {
type2 child = this.getChild();
type3 var = this.something();
// `this` may now be garbage collected
return child.somethingElse(var); // segfault comes here
}
> Where the destructor method of this calls a method that will free() native memory that is also accessed by child; if this is garbage collected before child.somethingElse() runs, the backing native code will try to access memory that has been free()ed, and receive a segmentation fault.
If child needs some block of shared memory contained in the parent (this)... shouldn't there be a shared object referenced by both parent and child that owns the block of shared memory? Then as long as child isn't GC'd, even if the parent/this is GC'd, the shared memory-owner won't be GC'd, and the memory will be safe.
For the C++ equivalent of this pattern, you'd want to scope the shared memory to a reference-counted RAII resource (say, a shared_ptr), and make sure that any actor that interacts with it holds a reference for the actor's lifetime. It's unreasonable for Java to "guess" that you meant anything different from this pattern - what if you actually wanted the parent object to be eligible for GC (say, if it's hogging other resources the child doesn't need) between this.something() and child.somethingElse()?
So I'd consider this a WontFix if I were a JVM developer, and maybe write a blog post about it and put it on HN if I had the time. Something something feature not a bug, etc.
EDIT: To be clear, the child is trying to have low-level access to a resource it has no ownership stake in, implicitly or explicitly. So there's no reason for that resource to stick around for the child. It's like a spouse taking the house in a divorce - the "prenup" in Java is that only reference-holders have any expectation for an object to be accessible to them. If the "child" didn't want to find itself segfaulted on the streets, it should have thought about writing that "house" (the shared memory) into its prenup, hmm?
EDIT 2: The analogy kind of fell apart, I think. But my point still stands. Apologies to any divorced HN'ers I may have offended.