Detailed description of heap memory and stack memory in Java

Source: Internet
Author: User

Some of the basic types of "variables" defined in "Functions" and "reference variables" of objects are allocated in the stack memory of the function.

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 store objects and arrays created by "new".

The memory allocated in the heap is managed by the Java Virtual machine "GC". After creating an array or object in the heap, you can also define a special variable in the stack, which is equal to the array or the first address of the object in the heap memory, and the special 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.

A reference variable is a normal variable that is allocated in the stack when defined, and the reference variable is released when the program runs 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 new to produce arrays and objects, the heap memory used by the array and the object itself is not freed, and arrays and objects become "garbage" and cannot be used again when there is no reference variable pointing to it, "but" is still occupying memory and 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!


2 comparison of heaps and stacks

From the "Function and function" of heaps and stacks to a popular comparison,The heap is mainly used to store "objects", the stack is mainly used to execute "program"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 that allocate memory space from the stack. 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, but it is said that although the allocation is carried out at the time of the program running, the size of the allocation is determined, unchanged, and the "size of how much" is determined at compile time, not at runtime.

Heap is when the application is running to request the operating system to allocate its own memory, because of the memory allocation from the operating system management, so the allocation and destruction of time, so the efficiency of the heap is very low. But the advantage of the heap is that the compiler does not have to know how much storage space to allocate from the heap. It is also not necessary to know how long the stored data will stay in the heap, so there is greater flexibility in storing the data with the heap. 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 also the advantages of people (halo ~).

3 stacks and stacks in the JVM

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 compilation principle.

From this allocation mechanism in Java, the stack can be understood as a stack is a storage area that the operating system establishes for a process, or a thread (a thread in a multithreaded operating system) for this thread, which 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 in Java

Java divides memory into two types: one is stack memory, and the other is heap memory.

Some of the basic types of variables and object reference variables 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 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 objects and arrays created by new.

The memory allocated in the heap is managed by the automatic garbage collector of the Java Virtual machine.

After generating an array or an object 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.

A reference variable is a name that is an array or an object, and you can use reference variables from the stack to access the arrays or objects in the heap later in your program.

In particular, say:

Stacks and heaps are 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, after the register, 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. Let's say 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. While an object reference variable modifies the internal state of the object, it affects another object reference variable

Detailed description of heap memory and stack memory in Java

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.