开发者

Concept check: Java's heap-only memory allocation model doesn't mean it has no function call stack, right?

开发者 https://www.devze.com 2023-01-04 10:03 出处:网络
I\'m a bit confused on the degree of \"absolutes\" here. I know that memory allocation in C++ can be do开发者_如何学运维ne by either heap or stack.

I'm a bit confused on the degree of "absolutes" here.

I know that memory allocation in C++ can be do开发者_如何学运维ne by either heap or stack. And I know that Java's memory allocation can only be done via the heap.

Basically, is the following correct?

"Java doesn't have stack-based memory allocation [that programmers can directly access]" shouldn't be conflated with "Java still uses a function call stack to implement function calls, just like every other language".

http://en.wikipedia.org/wiki/Stack-based_memory_allocation http://en.wikipedia.org/wiki/Dynamic_memory_allocation


Java saves local primitives on the call stack. So, not everything is on the heap.

The main difference between the memory model of Java and C++ is that in Java you cannot choose where to save your objects, Java decides for you.


I would say programmers can directly access it. You can't place arrays on the stack, but you can declare local variables, whether primitives or references. E.g.:

static void foo(double baz)
{
  int foo = ...;
  JFrame baz = ...;
}

foo, bar, and baz are all placed on the stack (while the JFrame object is placed on the heap).

You're right that it uses a stack frame quite similarly to most languages. In fact, the JVM itself is stack-oriented, meaning that operations work on the top of the stack (rather the contents of registers). For example, ladd pops the top two stack elements, adds them, then pushes the result. And we shouldn't forget our old friend StackOverflowError.


Java does indeed have a function call stack, even though all memory allocations happen on the heap. Here's an example

static LinkedList<Object> foo(int x)        // x is pushed onto the stack
{
    int y = x;                // this is a basic data type, so it goes on the stack
    Object o = new Object();  // the Object is in the heap, but the pointer to it is on the stack
    List<Object> xs = new LinkedList<Object>();  // ditto
    xs.append(o);             // a copy of the pointer to my object is now in the LinkedList on the heap
    return xs;                // the pointer to the structure is returned through the stack
}
0

精彩评论

暂无评论...
验证码 换一张
取 消