JVM Learning (2) -- What is stack, stack, and stack, which are often mentioned in technical articles, summary from the OS perspective, and jvm technical articles
As the saying goes, the self-written code is also others' code six months later ...... Review! Review! Review!The knowledge points involved are summarized as follows:
- Stack is a stack
- JVM stack and local method stack Division
- Java stack, stack, and c/c ++ Stack
- Data Layer heap and stack
- OS-level heap and stack
- How does the JVM stack correspond to the OS?
- Stack is required for method calls
It's a problem with menstruation. Someone has asked me this kind of basic knowledge. However, I can't answer this question consciously. Now, let's make a simple conclusion:
The previous article concluded that the JVM memory is mainly divided into three partitions.
- Heap: stores only the object (array) itself (reference type data), and does not store references of Basic Types and objects. The JVM has only one heap zone. This "heap" is a heap in the sense of dynamic memory allocation-the memory zone used to manage the dynamic lifecycle. The JVM heap is shared by all Java threads in the same JVM instance. It is usually managed by an automatic memory management mechanism, which is usually called "garbage collection" (GC ). The JVM specification does not require JVM to implement the GC algorithm.
- Stack: only objects and object references of the basic data type are saved in the Stack. Each thread has one stack zone. Data in each stack zone is private and cannot be accessed by other stacks. Frames in the stack (stack frames are generated by method calls) are divided into three parts: basic variable zone, execution environment context, and operation instruction zone.
- The method area, also known as the static area, is shared by all threads like the heap. The method area contains all the class and static variables. The method area contains always unique elements throughout the program. For example, class or satic.
What is a stack? Is it a heap or a stack?
I was misled when I was a beginner in c ++, saying that the stack is a heap ...... In fact, this is a misunderstanding of translation,Stack, in fact, should be translated into a stack more appropriate, and the stack is separated, because the English stack is the meaning of the stack,Located in RAM (Random Access Memory), the speed is second only to registers. Store basic variables and references. Data in the stack can be shared. However,The data size and lifecycle in the stack must be determined, which is the disadvantage of the stack..
A stack is not a heap, but a stack. Heap stores all java objects (except escape analysis ).
How are the local method stacks and JVM stacks divided?JVM specification writing: each Java thread has its own independent JVM stack, that is, the call stack of the Java method. At the same time, in order to allow native code to call Java code and allow Java code to call native methods, the JVM specification also requires that each Java thread has its own independent native METHOD stack. It is a concept defined in the JVM specification. It does not mean that the specific JVM implementation really requires two independent stacks for each Java thread. Taking Oracle JDK/OpenJDK's HotSpot VM as an example, it uses the so-called"
Mixed stack"--
Stack frames of Java methods and stack frames of native methods are stored in the same call stack. Therefore, each Java thread has only one call stack.Integrates the JVM standard JVM stack and native method stack concepts. For example, the structure of article 1:
Stack and stack at the data layerData structure.
Stack, which is translated into a stack in Chinese, actually refers to the stack. Here we talk about the stack of the data structure, not the heap and stack in the memory allocation. Stack is the structure of advanced and later data. For example, you can pile up your dishes one by one and put the last one at the top.
The stack data structure is relatively simple. Heap translation to heap, yes
An ordered tree.
Does the JVM stack have the same heap and stack as c and c ++?Before answering this question, you must first answer the memory allocation policy when the program is running. The theory of the compilation principle is as follows:
There are three policies for allocating the program running memory:
- Static storage allocation:During compilation, you can determine the storage space requirements of each data target at the runtime. Therefore, you can allocate a fixed memory space to each data target during compilation. This allocation policy requires that no variable data structures (such as variable arrays) or nested or recursive structures are allowed in the program code. Because they both make compilation programs unable to calculate accurate storage space requirements.
- Stack-based storage allocation: Also called dynamic storage allocation,Opposite to static storage allocation,Stack is temporary!In stack-based storage, local variables and temporary variables are stored, such as basic data types and object references ...... From the perspective of memory allocation, because the basic data type is stored, the compiler knows the type size in advance, so it can directly perform effective memory allocation, such as int, the computer knows the scope of the memory, so the system allocates the memory directly to the stack, and no program needs to apply for xxx memory on its own! The reference type, for example, defines a class by yourself. Obviously, this class does not know the size. You should have a program to apply for memory space, so it is allocated by the heap! Stack allocation mode specifies that when a program module is running, you must know the size of the Data zone required by the program module to allocate memory for it. Like the stack we are familiar with in the data structure, stack-based storage allocation is distributed based on the principle of first-in-first-out.
- Heap Storage Allocation:The module is responsible for determining the memory allocation of the data structure required for storage at the compilation or runtime module entrance, such as variable length strings and object instances. The heap consists of a large part of available blocks or idle blocks. The memory in the heap can be allocated and released in any order.
Therefore, we conclude that:The stack is mainly used to store objects, and the stack is mainly used to execute programs.This difference is mainly determined by the features of stacks and stacks: for example, C/C ++ ...... All method calls are performed through stacks, and all local variables and formal parameters are allocated memory space from stacks, just like the conveyor belt band in the factory, stack Top Pointer will automatically guide you to the position where you put things. All you have to do is put things down. When you exit the function, you can modify the stack top pointer to destroy the stack content. This mode is the fastest, of course, used to run the program.
Now let's get down to the point. Previous Article 1 has summarized that JVM is a stack-based virtual machine. Each JVM instance allocates a stack for each newly created thread, and multiple threads share the unique heap zone. That is to say, for a Java program, it runs through stack operations. The stack stores the thread status in frames. JVM only performs two types of operations on the stack: frame-based stack pressure and outbound stack operations. When a thread is executing a method, this thread is called the current method, and the frame used by the current method is called the current frame. When a thread needs to call a Java method, JVM will first press a new frame in the Java stack of the thread. This frame naturally becomes the current frame. During the execution of this method, this frame will be used to save the method parameters, local variables, intermediate calculation processes and other data ...... This frame is similar to the activity record concept in the compilation principle.
Well, for a long time, from the Stack-based allocation mechanism, the Stack can be understood as follows: Stack) it is the storage area established by the operating system for a process or thread (a thread in a multi-threaded operating system) when the operating system creates a thread. This area has advanced features. The newly added data items in the stack are placed on the top of other data items. You can only remove the data at the top of the stack when removing the data ). Similar to this paper:
In addition, every JVM instance has only one heap, and this unique heap is shared by global threads! All the class instances or arrays created by the program during running are stored in the heap and shared by all the threads of the application. There is no fixed sequence of data items in the heap. you can insert and delete data in any order because they do not have the concept of "TOP" data.
Unlike C/C ++, the heap memory allocation in Java is managed automatically (the automatic garbage collector of Java Virtual Machine is managed, but the disadvantage is that the memory needs to be dynamically allocated at runtime, slow access) in Java, the storage space of all objects is allocated in the heap, but the object reference is allocated in the stack, and the memory allocated in the heap is the actual object itself, the memory allocated in the stack is only a pointer (reference) variable pointing to this object.(The value of the variable is equal to the first address of the array or object in the heap memory.). The heap memory management of c ++ requires manual management by programmers. The new and delete operators ......
What are the features of stack allocation in memory management? What are the advantages and disadvantages?
The first thought is the feature of the fast memory FILO, and after such a long-winded beep, another conclusion is drawn:Data in the stack can be shared.
int a = 3; int b = 3;
The compiler first processes int a = 3; creates a reference with the variable a in the stack, and then finds whether the value 3 exists in the stack. If not, it stores the value 3, then point a to 3. Then process int B = 3. After the referenced variable of B is created, B is directed to 3 because there is already 3 in the stack. In this way, both a and B point to 3 at the same time. At this time, if a is set to 4 again, the compiler will re-search whether there are 4 values in the stack. If not, it will store 4 and make a point to 4; if yes, direct a to this address. Therefore, changing the value of a does not affect the value of B.Note that the sharing of data is different from the sharing of two objects pointing to one object at the same time, because the modification of a does not affect B, which is completed by the compiler, it facilitates space saving. A variable referenced by an object modifies the internal state of the object, which affects the variable referenced by another object.
Advantages: high speed, no memory management, the disadvantage is that too small, method calling is too high, easy to memory overflow, and stack is temporary, data has a life cycle, and is a temporary storage.
From the perspective of physical computer memory, where are the stacks and stacks?
-
Is it usually controlled by the operating system (OS) and language runtime?
-
What is the scope of their functions?
-
What determines their size?
-
Which is faster?
- How does the JVM stack correspond to OS?
Before answering this question, we must first know that the memory management mechanism varies with compiler and processor architectures! To help you understand, first summarize the following principles:
What is the principle of locality?
The operating system textbook writes the local principle like this: when the CPU accesses the memory, the accessed storage units tend to gather in a small continuous area, whether it is access commands or access data.
I understand it like this: the computer's storage system is small to large, divided into registers, level 1 cache, level 2 cache, Level 3 cache, memory, disk ...... The register is the place where the CPU stores computing data. The CPU has to work and the data or address is required. First, find it from the level-1 cache. If it cannot be found, find it from the level-2 cache, if Level 2 is not found, go to Level 3 to find ...... If the target data is found on the disk, the data is first stored in the memory, then stored in the third-level cache, second-level cache, and first-level cache, and finally in the register before being used by the CPU. It can be said that the first-level cache is the register cache, the second-level cache is the first-level cache, and the third-level cache is the second-level cache ...... The lower layer is the cache of the above layer. In general, the local principle is that the CPU runs very fast! Is saved at high speed! However, the access speed between the disk and memory is very slow (I/O bottleneck cannot be exceeded ......), If the CPU needs more data on the disk, memory ...... This will take a lot of time to wait, so we have set a high-speed cache! When the CPU frequently uses a piece of data, the computer may save the data on it and its nearby addresses to the cache, because it is very likely to predict that the data will be used again, the computer will store the data closer to the Register level, that is, the data accessed by the cpu, all tend to be concentrated in a small continuous area, which is also the true meaning of cache. Now the question is answered:
How can a computer determine whether a piece of data may be used in the future?
- Time locality: If a data is being accessed, it is likely to be accessed again in the near future. Of course, this is correct, and the used data may be used again.
- Spatial locality: the information that will be used in the near future may be close to the currently used information on the spatial address. The data next to the currently used data address, of course, it is also very likely to be used. For example, an array or something ......
Oh. The previous problems have come to the conclusion that the stack and heap are used to obtain the memory from the underlying operating system. In a multi-threaded environment, each thread can have its own independent stack, but they share the heap. Parallel access is controlled by the heap instead of the stack.
- Heap:Contains a linked list to maintain used and idle memory blocks.
The newly allocated memory (with new or malloc) on the heap is to find some suitable blocks from idle memory blocks that meet the requirements. This operation updates the block linked list in the heap. These metadata is also stored on the stack, and is often located in a small area in the header of each block. New blocks are added to the heap, which are usually extended from low addresses to high addresses, that isThe heap is growing upwards!Therefore, we can consider that the heap size increases with memory allocation. If the applied memory size is small, it usually gets more memory than the applied memory size from the underlying operating system. Applying for and Releasing many small blocks may produce the following status: there are many small and wasted idle blocks between used blocks ...... As a result, the application for large memory blocks fails. Although the total number of idle blocks is sufficient, the idle blocks are scattered and cannot meet the applied size. This is called"Memory fragmentation". When the used blocks of idle blocks are released next to them, the new idle blocks may be merged with adjacent idle blocks into a large idle block, this can effectively reduce the generation of "fragments.
Heap management depends on the runtime environment. C uses malloc, free, and C ++ to use new and delete, but many languages have garbage collection mechanisms, such as Java GC.
The CPU uses the push command to press the data stack, and uses the pop command to play the stack. When pushing the stack, the sp value is reduced (extended to the low address ). When the pop stack is used, the sp value increases.The value of the CPU register is used to store and obtain data..
-
- When a function is called, the CPU uses a specific command to press the current IP address on the stack, and then assigns the address of the function to the IP address so that the cpu can call the function. When the function returns, the old IP address is pushed to the stack, and the CPU continues to remove the code before the function is called.
- When entering the function, sp expands down to ensure that sufficient space is reserved for the local variables of the function. If the function has a 32-bit local variable, it will leave enough space in the stack. When the function returns, sp releases space by returning the original position.
- If a function has parameters, the parameter is pushed to the stack before the function is called. The code in the function uses the current position of sp to locate parameters and access them.
- For nested function calls, function parameters are assigned to each newly called function. The return value address, local variable space, and nested call activity records are pushed into the stack. When the function returns, it is revoked in the correct way.
The stack is subject to memory block restrictions, continuous function nesting ...... Allocating too much space for local variables may cause stack overflow. When the memory area in the stack has been used up, it will trigger a CPU exception. ThisExceptions are converted to stack overflow exceptions of various types through language runtime.. In general, the stack is closely integrated with the processor architecture with lower-level features, and the space can be extended when the heap is insufficient. However, the extended stack is generally impossible, because when the stack overflows, the execution thread is shut down by the operating system, which is too late.
Now you can answer these questions:
Is it usually controlled by the operating system (OS) and language runtime?
As mentioned above, heap and stack are collectively referred to as there are many implementation methods. A computer program usually has a stack called the call stack, which is used to store information related to the current function call (for example, the address of the main function and the local variable), because the function needs to be returned to the main function after being called. Stack carries information through expansion and contraction. In fact, the program is not controlled by the runtime, but determined by the programming language, operating system, or even system architecture. Heap is dynamically and randomly allocated (memory) in any memory, that is, unordered. The memory is usually allocated by the operating system and allocated by calling the API through the application. There will be some additional overhead in managing the Dynamic Allocation of memory, but this is handled by the operating system.
What is the scope of their functions?
The call stack is a low-level concept. As far as the program is concerned, it has nothing to do with the "scope of action. For advanced languages, languages have their own range rules. Once the function returns, the local variables in the function are released directly. It is also difficult to define in the heap. The function scope is limited by the operating system, but the programming language may add some rules to limit the scope of the heap in the application. The architecture and operating system use virtual addresses, which are then translated from the processor to the actual physical address, and there are page errors. They record the page that belongs to the application. But you don't need to worry about this, because you only allocate and release the memory in the programming language, and some error checks (Reasons for allocation failure and release failure ).
What determines their size?
Depends on the language, compiler, operating system, and architecture. Stack is usually allocated in advance, because the stack must be a continuous memory block. The compiler or operating system of a language determines its size. Do not store large data blocks on the stack. This ensures that there is sufficient space to avoid overflow, unless infinite recursion occurs or otherwise. Heap is a collective term for any memory that can be dynamically allocated. Its size is changed. The operating system and the Modern processor work in a highly abstract way, so you do not need to worry about the actual size under normal circumstances, unless you have to use the memory you have not allocated or the memory has been released.
Which one is faster?
Stack is faster because all idle memory is continuous, so you do not need to maintain idle memory blocks through the list. It's just a simple pointer to the top of the current stack. The compiler usually uses a dedicated and fast register SP. More importantly, subsequent operations on the stack will follow the local principle.
How does the JVM stack correspond to OS?
Take the Virtual Memory Distribution of a process in linux as an example:
In the figure, the address 0 is at the bottom, and the larger the memory address is. Taking a 32-bit operating system as an example, a process can have a virtual memory address range of 0-2 ^ 32. It is divided into two parts, one is left for the kernel virtual memory, and the other is the process itself, that is, the process virtual memory in the figure.
Common Java programs use process virtual memory.The top part of the memory is called the user stack. This is the stack. The 32-bit stack top pointer register is esp, with runtime heap in the middle. It is a heap. Note that they are not the same as the stack and heap in the data structure. As summarized above,
Stack is downward, and heap is upward.When a program calls a function, each function has a call frame on the stack ).
Summary, summed up so much, now the last question: Stack is required for method callsActually, it is not a method call.
Stack requiredInstead, it is designed to be implemented using stacks! We know that the activity records (I .e. local or automatic variables) of each method are allocated to the stack. This not only stores these variables, but also can be used for tracking nested methods. As we can see through observation, the call process of the method is as follows: 1. Calculate the parameter and pass the Parameter
2. Return address of the Save Method
3. transfer control to callee
4. Save the necessary caller site
The order between the above steps is variable,
Theoretically, no step must be implemented using stacks.Theoretically, if there are many registers, We can discard the stack, but we don't actually do it. From a realistic perspective, stack is a suitable implementation method, simply put, the survival time of local data of method calls satisfies the "first-in-the-second (FILO)" order. The reason why Stack is used for recording is that the basic operations of stack support access in this order. Heap cannot be implemented.
This article summarizes references: Java programming ideas, modern operating systems, computer systems, and modern compilation principles. deep understanding of Java virtual machine, JVM specification 7, zhihu, stackoverflow ......