Java basics-heap memory and stack memory

Java divides memory into two types: stack memory and heap memory. Both heap and stack are used by Java to store data in Ram.
1. Introduction:
All parts of the application use heap memory, and then the stack memory runs through a thread.
When passing parameters in function calls in java, the principle of value transfer is followed.
Therefore, the basic type transfers the data value itself (eg: a=1, b=a, when b=1+2, just b =3, a is still 1) The
reference type transfer is the reference of the object, that is, the address of the linked list is passed (eg: objectA=tomato, B=objectA, but the memory address of A is given to B)
1. The stack memory is
in the function Some defined basic type variables and object reference variables are allocated in the stack memory of the function.
2. Heap memory
(1) Heap allows the program to dynamically apply for a certain size of memory space at runtime. Heap memory is actually a data structure of priority queue that meets the nature of heap memory .
(2) Dynamic application of heap memory for memory space :
First, know that the operating system has a linked list that records free memory addresses;
second: When the system receives a program request, it traverses the linked list to find the first heap node whose space is larger than the requested space.
Again: The found heap node is deleted from the free node list, and the space of the node is allocated to the program.
ps: To facilitate the release of space later, the size of this allocation is recorded at the first address of the allocated space.
ps: When the space found> the space applied for, the system automatically re-places the excess space into the space linked list.

Second, the comparison of heap memory and stack memory

Stack memory Heap memory
Stored content Temporary variables, local variables (basic type variables, object references), method calls Store all new objects (ie instance variables) and arrays, and the allocation method is similar to a linked list
Entry-exit principle First in, first out (similar to a bucket) The data structure extended to the high address is a discontinuous memory space, and the traversal direction of the linked list is from the low address to the high address
for example For example, the test0 function is called in the main function, and test0 is released first, and then the main is released. ----
Recycling mechanism When the scope of the variable is exceeded, the stack memory space is automatically released The garbage collector automatically collects data that is no longer used
Scope of use Stack memory cannot be accessed by other threads The formation in the heap memory is globally accessible
Memory overflow When the stack memory is full, throw java.lang.StackOverFlowError exception When the heap memory is full, throw java.lang.OutOfMemoryError: JavaHeapSpace error
Pros and cons Small stack memory Heap memory acquisition space is more flexible, relatively large ()
Short life cycle Heap memory from the beginning of the program run to the end of the run
Fast access speed Slow access speed (easy to produce memory fragmentation, but it is convenient to use)
Stack data can be shared, but the size and lifetime of the data stored in the stack must be determined from time to time, which lacks flexibility

3. Memory analysis example
(1) Code implementation
This example is a class that defines a point in a three-dimensional space, and realizes the modification of coordinates and the distance between the point and the origin.
The idea of ​​writing this example:
1). The attributes analyzed are: point, three coordinates (x, y, z).
Methods: point initialization (construction method), coordinate modification (set), coordinate value acquisition (get) , Find the sum of the squares of the distance
2) to achieve, the specific code is as follows

package OOP;

 class Point {
    
    
    private double  coordinateX ;
    private double  coordinateY ;
    private double  coordinateZ ;

    Point(double x,double y,double z){
    
    
      coordinateX = x;
      coordinateY = y;
      coordinateZ = z;
    }

    public void setCoordinateX(double coordinateX) {
    
    
        this.coordinateX = coordinateX;
    }

    public double getCoordinateX() {
    
    
        return coordinateX;
    }

    public void setCoordinateY(double coordinateY) {
    
    
        this.coordinateY = coordinateY;
    }

    public double getCoordinateY() {
    
    
        return coordinateY;
    }

    public void setCoordinateZ(double coordinateZ) {
    
    
        this.coordinateZ = coordinateZ;
    }

    public double getCoordinateZ() {
    
    
        return coordinateZ;
    }

    //计算点到原点的距离的平方
    public double  distanceSquare(){
    
    
        double disSquare = coordinateX*coordinateX +coordinateY*coordinateY +coordinateZ*coordinateZ;
        return disSquare;

    }
}
public class TestPoint{
    
    
    public  static void main(String args[]){
    
    
        //生成特定坐标的点对象
        Point p1 = new Point(1,2,3);
        System.out.println("生成的点是"+"("+p1.getCoordinateX() + ","+p1.getCoordinateY()+ ","+p1.getCoordinateZ() +")");

        //设置坐标
        p1.setCoordinateX(6);
        System.out.println("p1的x轴应该是6    "+p1.getCoordinateX());

        //计算点到原点的平方
        double dis1 = p1.distanceSquare();
        System.out.println(dis1);

    }

2. Memory analysis
(1) The first step is to
Insert picture description here
define the p1 reference object, allocate a space 1b6d3586 in the stack memory, and apply for a space in the stack memory;
execute new point (1, 2, 3): allocate x, y in the stack memory , Z are 1, 2 and 3 respectively;
coordinateX=x value 1, coordinateY=y value 2, coordinateZ=z value 3,
Insert picture description here

After the construction point is completed, the x, y, and z stack memory is released
Insert picture description here
(2) The second step is to call getCoordinateX()
p1.getCoordinateX(), the value is read, and the memory remains unchanged
(3) The third step: call setCoordinateX(6)
1) Pass Enter parameter 6, first add a space in the stack memory to store the passed parameter 6
Insert picture description here

2) Execute the following method:
public void setCoordinateX(double coordinateX) { this.coordinateX = coordinateX; } t rewrite the coordinateX of p1 to the newly passed 6 (this reflects the principle of value transfer in the java call) at this time memory for:



Insert picture description here
3) After the method is executed, the storage space of 6 is released in the stack memory.
Insert picture description here
4. The fourth step is to read the coordinates, and the memory remains unchanged.
5. The fifth step is to calculate the distance
double dis1 = p1.distanceSquare();
add dis1 to the stack memory, Store the calculation result on dis1.
Insert picture description here
6. Step 6: After the program is executed, release all the memory.
When System.out.println(dis1); After the last sentence is executed, the stack memory will release dis1, p1; the
heap collector will garbage the unused heap memory data Recycling.

At this point, the memory has been restored as before, empty. . . Haha, what
is wrong, please advise.

Guess you like

Origin blog.csdn.net/qq_44801116/article/details/114190628