Analysis of Java Object Memory Management Stack and Method Area

Non-stack one stack

Analysis of Java Object Memory Management Heap

Please open this link to jump to the previous chapter:
https://blog.csdn.net/QQ1043051018/article/details/112341273

The stack is dedicated to storing local variables in methods

The stack space is used to store the program and all local variables declared in the method when the program is running.
Local variables: are the variables declared in the method,
including parameter variables, variables declared in the method body, and variables declared in braces in the code segment.
The member variables are stored in the stack, and the life cycle is the same as that of the method.

For example: Review the method of cooking rice. What happens if it is called in the main method?

package day05;

public class buy {
    
    
    public static void main(String[] args) {
    
    
          /*栈测试*/
        double card=10; //饭卡里有10块钱
        char lp = buy('鱼',card);
        System.out.println("card的余额: "+card); // 7
    }

    /**
     * 帮同学打饭
     * @param what  菜名
     * @param card  饭卡余额
     * @return 打到的菜名
     */
    public static char buy(char what, double card) {
    
    
        card -=3; //每次减3元
        System.out.println("余额"+card); //10
        return what;
    }
}

Output result:
Local variable scope: only limited to the defined braces, and the sub-brackets of this brace are valid.
Insert picture description here

The life cycle of local variables

Every time a method is called in a Java program, the JVM allocates the required space for the current method in the stack. This space is called the "stack frame" of the method. A stack frame specifically corresponds to a method being called. Data variables such as parameters and local variables of the method are stored in the stack frame. When the method call is completed, the stack frame of the method will be cleared, and the local variables will become invalid at the same time.

Let's start the simulation:
First, the program executes the main method first, and creates 2 stack frames for the main method.
Insert picture description here
Second, the implementation of an assignment
Insert picture description here
buy continues to call the method
Insert picture description hereafter method when the call is completed, the stack frame method will be cleared.
Insert picture description here

Member variables and local variables

The differences between member variables and local variables are as follows:

Local variables:

-Scope: Only limited to the defined braces, and valid within the parentheses of this brace.
-Storage location: stored in the stack (zhan) memory
-defined in a method or statement block;
-no default value, you must set the initial value yourself;
-when the method is called, it is stored in the stack, and the method call ends, from the stack Clear in the middle;
-life cycle: disappear at the end of the bracket

Member variables:

-Defined in the class, outside the method;
-There is a default initial value, which can not be explicitly initialized;
-After the class is instantiated, it is stored in the heap, and when the object is recycled, the member variable becomes invalid;

The difference between member variables, local variables, and static variables

Insert picture description here

Case study helping students cook:

First create a class that encapsulates the meal card information

/**
 * 封装饭卡信息的类
 */
public class Card {
    
    
    //创建2个成员变量
    String name;//饭卡的主人
    double bal; //饭卡的余额

    /**
     * 初始化所有成员变量的构造方法
     * @param name 饭卡的主人
     * @param bal  饭卡的余额
     */
    public Card(String name, double bal) {
    
    
        this.name = name;
        this.bal = bal;
    }
}

Perform a test to help students prepare meals, and whether the balance of the meal card is reduced by 3 yuan

public class buy {
    
    
    public static void main(String[] args) {
    
    
       /*栈测试*/
      //创建一个饭卡对象lpCard,封装饭卡的余额
      //把lpCard对象封装到Card类中
      Card lpCard=new Card("LP",10);
      //lpCard去打饭,鱼
      char lp=buy('鱼',lpCard);
      //打印饭卡的余额
        System.out.println("饭卡的余额"+lpCard.bal);
    }

    /**
     * 这个方法是 使用Card类型对象作为参数的buy方法
     * @param what
     * @param card
     * @return
     */
    public static char buy(char what,Card card){
    
    
        //从饭卡对象的bal属性中减3元
        card.bal-=3;
        //打印饭卡对象的余额属性
        System.out.println("余额: "+card.bal);
        return what; //返回打到的菜名

    }
    /**
     * 帮同学打饭
     * @param what  菜名
     * @param card  饭卡余额
     * @return 打到的菜名
     */
    public static char buy(char what, double card) {
    
    
        card -=3; //每次减3元
        System.out.println("余额"+card);
        return what; //返回打到的菜名
    }
}

Insert picture description here

Next, let's use a picture to see the principle of operation:

First, the program executes the main method to create a stack frame in the stack. The stack frame
Insert picture description here
contains two local variables lpCard and lp,
and then executes the first sentence: Card lpCard=new Card("LP",10);

When a new appears in the heap, it means that a storage space for a Card type object must be created in the heap.
And Card contains two member variables, name and bal.
Because new calls the parameterized structure at the same time, it is initialized by default, so These two member variables have initial values.

Insert picture description here
Next, call the buy method and pass the parameters. When the
buy method is called, the stack frame of the stack method is opened in the stack, and then the parameters and local variables of the buy are saved.
Insert picture description here
When the buy method is called, the address value in lpCard is passed.

Insert picture description hereThe result becomes this pattern: the
card variable and the lpCaed variable point to the same meal card object in the heap at the same time.
At this time, no matter which party modifies the meal card object, it will directly modify the same object, and of course they will affect each other.
Insert picture description hereNext, even if the call to the buy method ends, the unused method frame no longer exists, but the object on the stack still exists.
Because only gc can reclaim the objects in the stack, it is uncertain when it is reclaimed. Besides, lpCard is still calling.

Insert picture description here


to sum up:

Life case: The stack is actually like a restaurant seat. When people come on the stack, they are released when they leave.

We only say so much about the stack, and then we look at the method area

Non-heap-method area

What is the method area?

The method area is used to store class information.
Note: Store class information, not object information. Classes are templates for objects. Objects are actually created according to the description of the class.
The object is in the heap, and the class information is in the method area

When the Java program is running, the bytecode information of the class file (that is, the content of the .class) is first loaded through the class loader, and the class information is loaded into the method area after parsing.
Class information includes member variables and method definitions.

Insert picture description here

Let’s take a life case as an analogy:

In fact, this method and this kind of information are just like this signature dish poster in a restaurant. Many signature dishes posters are posted on the walls of restaurants with instructions. When the basic chef cooks this dish, they follow the picture on the wall. If you want to order, you can also refer to the photos on the wall.

Note: Usually the class information in the method area is only loaded once before the first instantiation. Do not reload frequently.

It's like the signature dishes posted on restaurants, usually the same.

In fact, the main method must be called at the beginning of the program, so first, the entire Test information will be loaded into the method area.
Then you can execute the description of showMem() in the Test class step by step in the following method area.
Insert picture description here
Although showMem() is called twice during the execution process, it does not matter how many times it is called anywhere.
The definition of the showMem() method in Test is only stored in the method area.

It's like in reality, there is always only one signature dish on the wall, and the chef will cook multiple dishes for many customers repeatedly in accordance with the look and practice of this picture.
So there is only one recipe, and the chef will follow the recipe and execute it repeatedly.
Insert picture description here

Finally, the life cycle of the class information in the method area, basically most of the class information is only loaded once before using the instantiated object for the first time, and then kept in the method area.

Finally, please keep in mind an overview:

Two rooms and one hall:

Insert picture description here

The largest and most flexible is the heap, followed by the stack, which are constantly changing as the program runs, and finally the method area, which is relatively fixed



Analysis of Java Object Memory Management Heap of Past Knowledge

Did not study or want to know more, please open this link to jump to the previous chapter:
https://blog.csdn.net/QQ1043051018/article/details/112341273

Guess you like

Origin blog.csdn.net/QQ1043051018/article/details/112384674