Conceptual validation: The memory allocation model using the Java heap does not mean that it does not have a function call stack, right?

I'm a little confused about the degree of β€œabsolutes” here.

I know that C ++ memory allocation can be done by a heap or a stack. And I know that Java memory allocation is only possible through a bunch.

In principle, is the following correct?

"Java does not have a stack-based memory allocation [that programmers can access directly]" should not be combined with "Java still uses a function call stack to implement function calls like any other language."

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

+3
source share
3 answers

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

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

+7
source

I would say that programmers can directly access it. You cannot place arrays on the stack, but you can declare local variables, be it primitives or references. For instance:.

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

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

, , . , JVM , , ( ). , ladd , , . StackOverflowError.

+4

Java does have a stack of function calls, although all memory allocations happen on the heap. Here is 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
source

Source: https://habr.com/ru/post/1751054/


All Articles