Java learning notes (4): memory management, java learning notes
In terms of memory, Java itself has a spam mechanism, which seems to be negligible on the surface, but if we understand it, it may sometimes get twice the result with half the effort.
So I took some time to sort out such materials.
I. Basic Concepts
1. Stack
An understanding of the stack can be imagined as an empty bucket with only one entry. There is a principle: "first, then,". Now, put things in it. For example, the order of putting is P, i, N, S, I, L, Y, etc. If you want to take out the letters, the order will be Y, L, I, S, N, I, P, as you can imagine, it is much simpler.
In Java programs, stacks are mainly used to store variables generated by basic types, such as int and char, and to store referenced variables of objects, however, the generated objects are not stored here.
2. Heap
The role of heap in Java is to store the objects and arrays newly generated by the program. For example, when a variable stored in the stack is assigned a value, the value is placed in the heap. Simply put, the execution of the program is the correlation between the stack and the heap.
3. Data Sharing
Code: int a = 3; int B = 3;
When processing, process the variable first. The program looks for whether there is variable a in the stack. If there is no, it creates a reference variable a, and then finds whether there is a value of 3 in the heap. If not, it creates a space for allocating memory and creating 3, a points to 3. Next, process B = 3, create B in the stack, and search for 3 in the heap. If yes, point directly to the address 3. In this case, a and B share an address, which is called data sharing. In this case, memory space is saved and Java running quality is improved.
However, it should be noted that the above description only describes the coexistence of data in the heap, and only the data in the heap can be shared, because the data in the stack is private and cannot be shared.
4. Static Memory
Static Memory refers to the memory used to determine the size of the memory space. In this way, the memory can be directly allocated according to its size at the beginning.
5. dynamic memory
The reason it is called "dynamic" is that its size is random, and it is allocated as much as it is needed, depending on the situation. Therefore, when the program starts to run, it cannot be confused, a fixed value can be reached only when he wants to use it, and then the memory is allocated to him.
Ii. Memory Mechanism
1. Basic understanding: we can imagine the pointer in the C language. Find the variable from the stack and point to the address corresponding to the variable, that is, their value.
In allocation, static variables are allocated to them directly during class loading, but dynamic variables are allocated only when they are used.