Reputation: 809
For a statement in a Java function:
Xxx xxx = new Xxx() {
public Abc abc(final Writer out) {
return new SomeFunction(out) {
boolean isDone = false;
public void start(final String name) {
/* blah blah blah */
}
};
}
};
Which variable, including the functions, are put on the heap, and which will be put on stack?
The reason I'm asking this is a segmentation fault in the JVM:
kernel: java[14209]: segfault at 00002aab04685ff8 rip 00002aaab308e4d0 rsp 00002aab04685ff0 error 6
00002aab04685ff8
and 00002aab04685ff0
are near, it seems that the stack is growing too fast. I try to investigate this part of code, and doubt whether it is the cause of problem when calling this function for many times. Is it possible that the stack is not cleared if it is referenced by some variables on the heap?
Upvotes: 5
Views: 2178
Reputation: 10218
The question of whether a particular object goes on the heap is a bit involved.
In general, in Java, all objects are allocated on the heap, because a method may return or store a pointer to the object. If the object had been put on the stack, it would be overridden the next time a stack frame is put there.
However, the HotSpot JIT compiler does something called Escape Analysis. This analysis finds out whether an object "escapes" the scope of the method by looking at the method's code. If an object doesn't escape, the compiler may safely allocate it on the stack.
Wikipedia has some more information about Escape Analysis in Java, also regarding multi-threading and locking.
Regarding the stack overflow: Stack frames on the call stack are always removed after the method finishes. Actually, there is not even a need to explicitly remove it. The next frame will just override what was previously there.
Also, although in other languages (like C) it is possible to cause the stack to overflow by putting very large objects on the stack, I don't think this could happen in Java. I expect the engineers at Sun (Oracle) to be smart enough to not make the VM store huge objects on the stack.
So the only possibility to have a stack overflow is to have too many nested method invocations. Since the stack space is big enough to handle any "normal" method invocation nesting, a stack overflow normally indicates an infinite (or very large) recursion in your code.
Upvotes: 7
Reputation: 52
name
, isDone
, out
, ABC
and a "pointer" to the anonymous someFunction
will all be on the Stack; the rest goes to heap.
Upvotes: 0