[Java] Stack and heap memory in Java

This article is for learning reference only!
Related tutorial address:
https://www.cnblogs.com/whgw/archive/2011/09/29/2194997.html
https://www.developer.com/java/stack-heap-java-memory/
https:/ /zhuanlan.zhihu.com/p/529280783

Java data types are stored in two different forms of memory during execution: the stack and the heap . They are usually maintained by the underlying platform running the Java Virtual Machine (JVM). This article provides some insight into these two memory types from a Java software development perspective.

How does the Java platform work?

Java programs run on the platform provided by the Java Virtual Machine (JVM). The platform is a manager that provides all the resources a java application needs to run. This means that the programs that developers write (or the applications we create) cannot directly access system resources (whether hardware or software) unless the platform it is running on provides it. For Java, the sequence is as follows:

Java Virtual Machine (JVM) Tutorial

The JVM layer makes Java platform independent. Other programming languages, such as C/C++, do not use such layers, so while they are portable, they are not themselves platform independent:

Java Virtual Machine Tutorial

Both cases have many advantages and disadvantages. Since the Java language and the JVM platform are developed by the same group of people, the preference for programmer convenience is evident. This led to a huge evolution; from what started as a language, Java has now become an ecosystem of its own. At the same time, programming languages ​​like C/C++ place more emphasis on optimal use of core units by enabling direct access to system resources, resulting in ultra-fast and efficient programs. But both have their uses in the world of software development.

As for languages ​​in general, all programming languages ​​share many similarities in the process of compilation and execution. One of the most important of these areas is memory management . Regardless of the language you use, memory management can have a significant impact on the overall efficiency of your program because it helps manage memory resources, thereby improving application performance. The more memory used, the slower the program.

What is runtime memory in Java?

A common phenomenon in applications is that each application needs some memory to work optimally. This memory is provided by the underlying platform. For Java, the JVM provides it (granted by the OS, of course). The typical five parts of JVM memory include: method area , heap , stack , PC registers , and native memory .

Now let's focus on the stack and heap parts. Memory is not like a blank sheet of paper, programmers only need to write down data to store data. Instead, memory needs to be structured before it can be used. Stack and heap are data structures followed when using memory. During program execution, the stored data is used for various purposes depending on the purpose of the program.

The JVM determines the runtime data area used during program execution. Some data areas are JVM-relative, which means they are created when the JVM starts and persist throughout the lifetime of the JVM. However, there are other data areas that are created and destroyed by each thread. The JVM can execute multiple threads of execution concurrently. This means that each thread has its own pc (program counter) register to maintain the location of the currently executing instruction, and a stack to hold static memory allocations.

What is stack memory in Java?

A stack is an in-memory structure where developers store elements (such as a stack of books) in a way that allows data to be retrieved only from the top of the stack—often called first-in, last - out (FILO or LIFO). Since each thread maintains a private JVM stack, it is used to store variables related to its static memory allocation. Method-specific primitive variables that we declare and use in our code are actually stored in the stack area. Also, references to objects that are actually stored in the heap memory are also stored in the stack area. Therefore, any locally allocated memory is stored on the stack.

The default size of stack memory can be changed using the JVM parameter **-Xss . Sometimes the stack can overflow if you allocate too many variables or if a method calls itself recursively. A common error that all Java programmers know is java.lang.StackOverFlowError**. This error pops up when the stack is full. Every method call in Java creates a new block in the stack. Therefore, a poorly designed recursive method call can easily exhaust all the stack, resulting in an overflow error.

What is heap memory in Java

The heap is an area of ​​memory created as soon as the JVM starts and persists until the JVM is destroyed*. *Unlike the stack, which is a property of individual threads (since each thread has its own stack), the heap is actually global storage managed by the JVM itself. This memory is used at runtime to allocate memory for objects. Thus, object instantiations can be user-defined classes, JDK or other library classes. In short, any object created using the new keyword is stored in heap memory. All threads running in the JVM can access objects in the heap memory. Access management is complex and uses very complex algorithms. This is where the JVM garbage collector comes into play.

The default size of the heap can be changed using the **-Xms and -Xmx** JVM parameters. The size of the heap increases or decreases as the number of objects are created and destroyed. If its maximum limit is reached and further allocations are attempted, a **java.lang.OutOfMemoryError** will be thrown.

Java heap string pool

It's worth noting that even though it's a class, any object instantiated from that class is treated differently for java.lang.String . The creators of the JVM found this to be the most commonly used class in Java programming. Therefore, special care should be taken to maintain its efficiency. Also, string operations are always slow compared to primitive types. Therefore, the magic must exist so that the use of string objects is similar or close to the efficiency and convenience it has in code when using primitive types. Therefore, to maintain the efficiency provided by the JVM, a special memory area within the heap called StringPool is used . Any string objects created are stored in the StringPool to be executed by the JVM. This improves performance compared to other objects created on the heap.

Java Heap and Stack Code Examples

To better illustrate the use of heap and stack memory in Java, let's write a simple program and decide which allocation goes to which memory - heap or stack:

package project1;
import java.util.Date;
public class Main{
    
    
    public static void main(String[] args){
    
    
        int x=10;
        int y=20;
        String greet = "Hello";
        Date d = new Date();
        diff(x, y);
    }
    public static int diff(int x1, int x2) {
    
    
        return x2-x1;
    }
}

This sample Java code works as follows:

  • As the program starts, the JVM loads Java Runtime Environment (JRE) classes into the heap.
  • When the **main()** method is encountered, a stack is created.
  • The local variables x and y are stored on the stack.
  • The string greet is allocated in the StringPool area of ​​the heap.
  • Date objects are allocated in the heap area while their references are stored on the stack**. **

Java Tutorial

END

Stack and heap are two areas used by Java programs during code execution. Besides these two, there are other memory areas such as method area , registers , native area , etc. Each has its specific purpose in a Java application. However, from a developer's perspective, the stack and heap are fundamental aspects of the JVM that must be understood. However, a solid understanding of all runtime memory specifications is always an advantage and will be the subject of future Java programming tutorials.

Guess you like

Origin blog.csdn.net/m0_47015897/article/details/131412085