Detailed description of heap memory and stack memory in Java

Source: Internet
Author: User

A detailed description of heap memory and stack memory in Java  java divides memory into two types, one called stack memory, and a reference variable called heap memory   some basic types defined in a function is allocated in the function's stack memory. When a variable is defined in a block of code, Java allocates a memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically frees the memory space allocated for that variable, which can be used immediately by another.   Heap memory is used to hold the objects and arrays created by new. The memory allocated in the heap is managed by the Java Virtual Machine automatic garbage collector. After creating an array or an object in the heap, you can also define a special variable in the stack that is equal to the array or the first address of the object in the heap memory, and this particular variable in the stack becomes the reference variable of the array or object. You can then use the reference variable in the stack memory in your program to access the array or object in the heap, which is the equivalent of an alias, or codename, of an array or object. The   reference variable is a normal variable that is defined when memory is allocated in the stack, and the reference variable is released in the program run to an extraterritorial scope. The array and object itself is allocated in the heap, and even if the program runs beyond the block of code that uses the new generation of arrays and objects, the heap memory that the array and the object itself occupies will not be freed, and arrays and objects become garbage, no longer used, but still occupy memory when no reference variable points to it. is released by the garbage collector at a later indeterminate time.  This is also the main reason for the memory of Java comparison, in fact, the variables in the stack point to the heap memory variables, this is the pointer in Java!   java memory allocation policy and heap and stack comparison   1 memory allocation policy   According to the compiling principle, there are three strategies for memory allocation in the program running, namely static, stack, and heap .  static storage allocation, which can determine the storage space requirement of each data target at run time at compile time.  As a result, they can be allocated a fixed amount of memory at compile time. This allocation policy requires that the presence of mutable data structures (such as variable groups) is not allowed in the program code, and that nested or recursive structures are not allowed to occur because they cause the compiler to be unable to calculate the exact storage space requirements .  A stack storage allocation can also be called dynamic storage allocation, which is implemented by a stack-like run stack. In contrast to static storage allocation, in a stack storage scenario, the requirements for the data area are completely unknown at compile time, only to be known when running, but when the rules are entered into a program module You must know the size of the data area that is required for the program module to allocate memory for it. Like the stacks we've known in data structures, stacks are storedAllocation is based on the principle of advanced post-out.   Static storage allocation requires that the storage requirements of all variables be known at compile time, and that the stack storage allocation requires that all storage requirements be known at the entrance of the process, while the heap storage allocation is specifically responsible for the memory allocation of the data structures that the storage requirements cannot be determined at the compile-time or runtime module entrances. such as variable-length strings and object instances. The heap consists of large chunks of available blocks or free blocks, and the memory in the heap can be allocated and freed in any order .  2 heap and stack comparison   the above definition from the compiling principle of the textbook summed up, in addition to static storage allocation, is very rigid and difficult to understand, The following aside static storage allocation, centralized comparison heap and stack:  from the heap and the function of the stack and the role of the popular comparison, the heap is mainly used to store objects, the stack is mainly used to execute the program. And this difference is mainly due to the characteristics of the heap and stack:  in programming, for example, C + +, All method calls are made through stacks, all local variables, and formal parameters are allocated from the stack memory space. It's actually not an assignment, just up the top of the stack, like a conveyor belt in the factory (conveyor belt), stack pointer will automatically guide you to where you put things, All you have to do is put things down. When you exit a function, you can destroy the contents of the stack by modifying the stack pointer. This mode is the fastest, of course, to run the program. It is important to note that when allocating a data area for a program module that is about to be called, The size of this data area should be known in advance, it is said that although the allocation is performed at the time of the program run, but the size of the allocation is determined, unchanged, and this "size" is determined at compile time, not at runtime .  Heap is the application at runtime to request the operating system to allocate its own memory, Because of the memory allocations that are managed from the operating system, it takes time to allocate and destroy, so the heap is inefficient. But the advantage of the heap is that the compiler does not have to know how much storage to allocate from the heap, or how long the stored data will stay in the heap, so You get more flexibility when you use heaps to save data. In fact, object-oriented polymorphism, heap memory allocation is essential, because the required storage space for polymorphic variables can only be determined after the object is created at run time. In C + +, when you require an object to be created, you only need to compile the relevant code with the new command. When you execute the code, the data is saved automatically in the heap. Of course, to achieve this flexibility, there will inevitably be a price: it takes longer to allocate storage space in the heap! This is the reason why we just said that the efficiency is low, it seems comrade Lenin said good, people's advantages are often human shortcomings, People's shortcomings are often the advantages of people (halo ~).  3 The heap and stack   JVM in the JVM is a stack-based virtual machine. The JVM allocates a stack for each newly created thread. In other words, for a Java program, it runs through the operation of the stack. The stack holds the state of the thread in frames. The JVM operates on the stack in only two ways: stack and stack operations in frames.   We know that the method that a thread is executing is called the current method of this thread. We may not know that the frame used by the current method is called the current frame. When a thread activates a Java method, the JVM presses a new frame into the Java stack of threads. This frame naturally becomes the current frame. During the execution of this method, this frame is used to hold parameters, local variables, intermediate calculation procedures, and other data. This frame is similar to the concept of the activity record in the compiling principle .  from the Java distribution mechanism, the stack can be understood as: stack ( Stack) is a storage area established by the operating system for this thread when a process is established or a thread (a thread in a multithreaded operating system) that has an advanced post-out feature.   Each Java application uniquely corresponds to a single JVM instance, and each instance uniquely corresponds to one heap. All instances or arrays of classes created by the application in the run are placed in this heap and shared by all threads of the application. Unlike C + +, allocating heap memory is automatically initialized in Java. The storage space for all objects in Java is allocated in the heap, but the reference to this object is allocated on the stack, that is, allocating memory from two places when an object is built, memory allocated in the heap actually establishes the object, and the memory allocated on the stack is just a pointer to the heap object (reference) Only.   Heap and Stack   Java in Java divides memory into two types: one is stack memory and the other is heap memory.   Reference variables for some of the basic types of variables and objects defined in the function are allocated in the stack memory of the function.   When a variable is defined in a block of code, Java allocates memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically frees up the allocated memory space for that variable, and the memory space can be used for other purposes immediately.   Heap memory is used to hold the objects and arrays created by new.   The memory allocated in the heap, managed by the automatic garbage collector of the Java Virtual machine.   After an array or object has been generated in the heap, you can also define a special variable in the stack that is equal to the first address of the array or object in the heap memory, and this variable in the stack becomes the reference variable of the array or object.   Reference variable is equivalent to an array or objectA name that can then be used in the program to access the array or object in the heap using reference variables from the stack.   Specifically,:  stacks and heaps are the places that Java uses to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set up stacks or heaps. The   Java heap is a run-time data area in which objects allocate space. These objects are established through directives such as new, NewArray, Anewarray, and Multianewarray, and they do not require program code to be explicitly released. Heap is responsible for garbage collection, the advantage of the heap is the ability to dynamically allocate memory size, the lifetime does not have to tell the compiler beforehand, because it is at runtime to allocate memory dynamically, Java garbage collector will automatically take away these no longer use data. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time. The advantage of the   stack is that the access speed is faster than the heap, second only to registers, and the stack data can be shared. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible.The stack mainly contains some basic types of variables (, int, short, long, byte, float, double, Boolean, char) and object handle. Stack has a very important particularity, is that there is data in the stack can be shared.   Suppose we define both: int a = 3;   int b = 3; The compiler processes int a = 3 First, it creates a reference to a variable in the stack, and then finds out if there is a value of 3 in the stack, and if it does not, it stores the 3 in and then points a to 3. then the int b = 3 is processed, and after the reference variable of B is created, because there are already 3 values in the stack, B points directly to 3. In this case, A and B both point to 3. At this point, if you make a=4 again, then the compiler will re-search the stack for 4 values, if not, then store 4 in, and a point to 4; Therefore the change of a value does not affect the value of B. It is important to note that this sharing of data with two object references also points to an object where this share is different, because the modification of a does not affect B, which is done by the compiler, which facilitates space saving.       An object reference variable modifies the internal state of the object, affecting another object reference variable.         Why can't a String be compared with = =? Look at the JDK source code to understand.  Public String () {       This.Offset = 0;       This.Count = 0;       This.value = New Char[0];    } What is used in the construction method? New char[]; New objects exist in heap memory, that is, comparisons involving objects, = = can only compare values of referenced objects. Comparisons of two heap objects cannot be compared by = =.

A detailed description of heap memory and stack memory in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.