Home>Article>Java> How to tell the difference between heap and stack in Java applications

How to tell the difference between heap and stack in Java applications

无忌哥哥
无忌哥哥 Original
2018-07-19 09:42:59 2243browse

1. The memory of reference variables of basic data types and objects in Java is allocated on the stack, and the variables are automatically released when they go out of scope; the memory of reference type variables is allocated on the heap or in the constant pool (string constant pool, basic type constant Pool), that is, the created objects are stored on the heap.

2. The management of stack memory is completed by pushing and popping the stack. The basic unit of the stack is the stack frame. When a function is called, a new stack frame is created by pushing the stack. After the call is completed, the stack frame is released by popping the stack. . The heap is used to store objects created during runtime, and new objects are placed on the heap. JVM is a heap-based virtual machine. Each Java program runs on a separate JVM instance. Each JVM instance also corresponds to a unique heap. If a Java program has multiple threads, then they all run on the same JVM instance. These threads share heap memory. Therefore, when multiple threads access heap memory, the data in the heap must be synchronized.

C The mid-heap memory is opened and released by developers. There is a garbage collection period in Java that automatically completes the release. Developers only need to apply for the heap space they want.

3. In Java, space is opened in the heap to store the new object, and then a variable is referenced in the stack to store the first address of the object address in the heap. The heap can be accessed through the address stored in the reference variable in the stack. Object, the reference variable in the stack is equivalent to a name of the object in the heap.

4. The access speed of the stack is faster than that of the heap. The stack size and lifetime must be determined. The heap can dynamically allocate memory at runtime. The lifetime does not need to be told to the compiler in advance, so access is slow.

The above is the detailed content of How to tell the difference between heap and stack in Java applications. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn