140 points · by luu · 11y ago · 76 comments
> Optimizing transformations of a program can be designed that reduce the number of objects that are reachable to be less than those which would naively be considered reachable. For example, a Java compiler or code generator may choose to set a variable or parameter that will no longer be used to null to cause the storage for such an object to be potentially reclaimable sooner.
Also, the "this" keyword is treated like a parameter. (See the end of section 2.6.1 of the JVM spec.)
What is less convenient is that Java doesn't have a handy method to ensure that an object is reachable, that the JVM won't optimize away or eliminate. .NET has GC.KeepAlive; AFAIK, Java doesn't have an equivalent. I asked a question about this on SO[1] some time ago. An approximate equivalent can be cobbled together, with probabilistic assignments to a volatile variable.
[1] http://stackoverflow.com/questions/22457002/whats-the-java-e...
The first issue is that finalizers should NEVER be relied upon to clean up system resources the way that you might in a language with deterministic garbage collection like C++. Instead, expect clients of interfaces that use system resources to manually call some 'close' like method. Use finalizers to warn clients that they are leaking. Josh Bloch has an excellent writeup on this[†]:
http://www.informit.com/articles/article.aspx?p=1216151&seqN...
The second thing, as I believe @btown is saying, is that the child object seems to depend on memory that it doesn't own a strong reference to. I bet the whole memory graph here is just a tangled mess. I used to think that that was just the nature of graphs. When I first started working with GC that couldn't handle these kind of cyclical structures without being explicitly told I thought that it was an absurd premature optimization. Then, this wise old hacker peered at my code, smacked me on the back of the head, and grumbled that if I couldn't clearly explain the reference hierarchy it wasn't just the software that would be befuddled, it was too complicated for his old brain as well.
I'm sure that this can't be true, but I am starting to suspect that all the tremendous work that has gone into fast pause-less concurrent GC has been for naught. I wish that when GC encountered a cycle it would just tell the programmer that they now have a leak, maybe even suggest where it could be fixed with one of those neat little IDE quick fixes, and continue chugging along.
tl;dr When you have a hard problem let someone else deal with it.
[†] Granted, Bloch does make an exception for 'native peers'. My understanding of that pattern, however, is that the key is not letting some other object walk off with a reference to your peer, which is exactly what has gone wrong here.
(Aside: Josh Bloch's Effective Java & Java Puzzlers are fantastic. They are worth reading for programmers who use any language.)
Exactly. Having made similar types of robotics interfaces myself, the memory graph for OP probably isn't as complicated/cyclic as you might think: multiple types of frames (at various stages of visualization processing) look into each others' memory buffers for efficiency. It's probably best modeled as an acyclic directed graph where frame objects reference (many-to-many) memory buffers. The problem is that unless you abstract out those buffers into garbage-collectible objects themselves, it's very tempting just to pass a weak reference (like a pointer from JNI) to the buffer owned by an EarlyStageFrame to the processing code in a LaterStageFrame. Thus the segfault when the EarlyStageFrame is garbage-collected.
> It's probably best modeled as an acyclic directed graph
My pet theory is that a good representation for most systems should maybe always be an acyclic directed graph?
Are you saying that cyclic data structures are always a bad idea? So no one should ever make a doubly-linked list?
Or, to take a case from a game I'm working on: I'm writing a set of GUI controls for the game's UI. There will almost always be at least a few controls on screen, so I have a WindowManager object that lives for the entire duration of the application and does, among other things, tasks like telling all of the controls to draw themselves, determining which control has focus, etc. The controls all have a reference to the WindowManager object (or whatever their direct parent is, once I start supporting more complex controls) so they can implement methods like onClick() { parent->removeGroupOfControls(); }
Even though the WindowManager is persistent, the individual controls come and go quite often. So if I was using a GC (I happen to be doing this in C++) that simply threw up its hands whenever it encountered a cycle, none of the controls would ever get garbage collected, leading to a huge memory leak over time.
Is this a case where you think cycles are appropriate? Or is there a better way to refactor this so it doesn't use cycles? (If someone has ideas for a better design, I would absolutely love to know.)
Reg. your example, I have generally found it effective to model UI hierarchies where the top level components refer to their children 'strongly' while the children refer 'weakly' to their parents. I am not familiar with the recent smart pointer stuff in c++ but I believe that these concepts have been cleanly modeled with abstractions such as this:
http://en.cppreference.com/w/cpp/memory/weak_ptr
N.B. A more difficult conundrum that I have encountered when dealing with UI hierarchies is whether or not child components should require a constant reference to their parent passed upon creation or you should be able to 'reparent' or even be in an initial parentless case. My current thinking is that this is a mistake and interactions such as drag and drop are better handled by sending a gesture up to your data layer which then regenerates the component in its new place. This might get ugly, however, if you have a heavily direct manipulation based UI which doesn't really need a data layer on top.
By the way, what has lead you down the road of UI toolkits? They are a fetish of mine. Feel free to shoot me an email if you'd like to connect.
Wow. Overreact much? :-)
Garbage collection works great for one use case: managing heap memory. Please, let's not return to a universe where you need to free each chunk of memory piecewise. That makes freeing memory O(n) in the number of chunks freed, where modern collectors can free unlimited numbers of objects in O(1) time. Compared to this, malloc and free are a little like keeping score in soccer by tracking every action that does not result in a ball entering a net.
The trouble is finalizers. Finalizers suck. They tie the management of one resource (say native memory or file handles) to an unrelated resource (heap memory). This has the terrible consequences highlighted by this story, plus others. It keeps the native resource tied up until the collector decides to run, for one thing. It also harms performance in secondary ways even when the finalizer isn't running. For example, finalizers typically defeat escape analysis, meaning objects with finalizers can't be stack-allocated.
It's a good idea to use finalizers mostly for detecting invalid final states of objects (like leaking resources), as long as you stay aware that finalizers can slow down your program in unexpected ways.
[These are my personal opinions, not those of my employer.]
A GC can't outdo that. For everything the GC frees, it has to do some work to answer the question, "Should I free this or not?" Even if that question can magically be answered with a single CPU instruction, that's still O(n) answers in the number of chunks freed.
http://en.wikipedia.org/wiki/Smart_pointer#C.2B.2B_smart_poi...
My personal experience with similar such systems was that even when performance was not a concern the cost of having to untangle and document my reference structure was well worth the time.
Has any language ever gotten the balance of tradeoffs for finalizers right for strong GC?
Why is that? I would have thought they would work really well together - if an object such as a file stream doesn't escape you could inline and run the finaliser after the last use of the object goes out of scope.
Or do you mean they defeat current implementations of escape analysis?
To make this work, the JIT would need to perform escape analysis on the finalizer too (since the finalizer can make an object escape). If that analysis succeeds, then I suppose the object could be stack-allocated and the finalizer called directly. Even then, though, you would have to think carefully about all the subtle ramifications, like the consequences running a finalizer on an application thread instead of the finalizer thread. (What if the finalizer grabs a lock in an attempt to protect itself from the application code? Now this becomes a recursive lock by one thread, and so both the application code and the finalizer can enter it at the same time!)
If this ever became important enough, it's possible the JIT developers could get this right in every case with enough effort invested. I wouldn't count on that happening any time soon.
[These are my personal opinions, not those of my employer.]
As I recall, the memory hierarchy was actually simple--the issue was that it called some structure_free(parent) in C++, which freed the entirety of that part of the hierarchy--the parent and the children; which would obviously cause problems if the children weren't done working.
That said, I'm looking over my backups from that era; I can't quite figure out what real code corresponds to the pseudo-code in the post (I didn't have the real code when I wrote the post).
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.
Even in native code, it is wrong to have a pointer to managed memory without using the Global/Local Ref() methods that the jvm provides.
In summary, the jvm is behaving correctly with respect to GC. Author doesn't know how to use JNI and has caused the crash.
>The dashboard was written in Java, and the source was available (under a 3-clause BSD license), so I dove in, (...)
Also, nowhere in the post he says that it is JVM's fault.
He says it was the JVM or the compiler's fault. He doesn't blame the code.
Raymond Chen explains it well here: http://blogs.msdn.com/b/oldnewthing/archive/2010/08/13/10049...
Unfortunatelly these types of bugs have a nasty way of showing up in other places where it can be even harder to debug. Long term these bugs need to be fixed otherwise your code will just be a ticking bomb. The worst part is when they combine with other bugs and they become even harder to debug.
You could say that the problem is that people abuse the garbage collector to manage something it shouldn't manage, or you could say that the problem is that garbage collectors are bad at managing anything that isn't memory. (I would lean towards the latter.)
I work on IBM's JIT compiler. We had to do something similar to fix this problem in DirectByteBuffer a few years ago, by adding a call to a magic method called keepAlive. To make this work, we had to teach the JIT to handle this method specially, or else it would have ripped it out, and the fix would have had no effect.
[These are my personal opinions, not those of my employer.]
Also, please note that both Clang and GCC use the same approach, except in their cases the programmer typically does not see the intermediary code (which is LLVM for Clang, and a family of intermediate languages for GCC).
(Also: it's not a stupid approach. Due to the way the JVM loads things, most of the time you don't know that any particular method won't be overridden later by something that does, in fact, have side effects. There are very few optimizations that could actually be done by the Java compiler.)
Especially as there's nothing preventing the "fix" from being optimized out by the JVM, which would reintroduce the problem all over again.
Since the VM apparently does optimization now, perhaps that won't get eliminated until the code path is hot, i.e., after a few thousand calls to the method.
Once we got a hack working, we ran with it and rarely tried to clean up. In this case, we didn't bother trying a different JVM.
[1] Unless the code is open source (as ours was), in which case we were explicitly allowed to use it.
Go pick apart aggressively optimized and inlined code and I bet you can find situations where 'this' never even exists.
this.getSize(); // bogus call to keep `this` around
could be optimized away since the value is never used.There have been 116 updates since then (33 public). Given that segfaults almost never happen in the JVM (I've never seen one) I can imagine it would be the highest priority to be fixed.
I've seen 5 segfaults over the last week in our system. Unfortunately we don't enable core dump in our system (yet) so we haven't really had a good sense of what might cause the system. We've been seeing about 30 SIGSEV's over the last three months, but we haven't been able to root cause it yet.