Ted Scofield wrote:Hi all,
I'm trying to figure out if my understanding of stack/heap in Java is sound, I'd appreciate any feedback/correction/remark.
First, some theory: in general, JVM stores objects/arrays in a heap, although some implementations may use a stack (escape analysis). Local variables are put in a stack. When a method is invoked, its parameters and local variables are pushed in a stack.
Consider the following example:
What happens when we invoke the program? JVM starts a new thread and creates its heap and stack.
Main method is executed first; a new String array object is created and stored in the heap. 'args' parameter is pushed in the stack, pointing to the newly created array.
Then a new Greeter object is created and stored in the heap. If there's not enough memory, an OutOfMemoryError is thrown. 'elvis' reference is put in the stack, pointing to the newly created object. If there's not enough memory in the stack, a StackOverflowError is thrown.
sayHello is executed on the 'elvis'.
A new String object is put in the String constant pool if it doesn't already exists
System.out is created or retrieved from heap and println method is triggered.
A new String object is added to String constant pool in the heap - "Hello Elvis".
After the println method is done, "Hello Elvis" will no longer be referenced by any variable. This makes it eligible for garbage collection.
When/if GC will be performed, this String object will be collected. The same goes for the Greeter object 'elvis' is pointing at.
I'm not sure for the last one though:
I assume the following: a new Greeter object is created on the heap and right away, the method sayHello is executed on it. The method does the same thing as I described above. When it finishes, the object becomes eligible for GC.
And finally, while it's good to have a general idea of the heap/stack landscape, you'll almost never actually care about it when you're developing with Java. About the only time it would come into play is if you're actually writing your own JVM implementation, or if you're working on a specialized or limited-memory JVM, or if you're doing hardcore profiling for memory or performance problems.
Ted Scofield wrote:To be honest, I'm preparing for an interview and it seems this question is pretty popular.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Probably because these questions are made up by people who learned their programming in the 70's-90's, who still haven't got their heads around the fact that, for many modern languages, these sorts of things simply aren't important.
If this was an interview for a perl job, a question like that would generate derisive laughter - and rightly so - so why do people think it's important for Java?
Consider Paul's rocket mass heater. |