Heap and Stack in Java

Source: Internet
Author: User

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:

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.

String is a special wrapper class data. Can be used:
String str = new String ("abc");
String str = "ABC";
Two forms, the first is to create new objects with new (), which is stored in the heap. A new object is created each time the call is made.
The second is to create an object reference to the string class in the stack str, and then find whether there is no "ABC" in the stack, if not, put "ABC" into the stack, and make str point to "ABC", if there is already "ABC" directly to the "ABC" Str.

Use the Equals () method when comparing values within a class, and when testing two wrapper classes for reference to the same object, use = =, the following example illustrates the above theory.

You can see that str1 and str2 are pointing to the same object.

The new method is to generate different objects. Each time one is generated.
So the second way to create multiple "abc" strings, in memory in fact there is only one object. This writing is advantageous and saves memory space. At the same time it can improve the speed of the program to some extent, because the JVM will automatically determine whether it is necessary to create new objects based on the actual data in the stack. In the case of string str = new String ("abc"), the code creates a new object in the heap, regardless of whether the string value is equal or not, and it is necessary to create a new object, thereby aggravating the burden of the program.
On the other hand, it is important to note that when you define a class using a format such as String str = "ABC", you always want to assume, of course, that the object that created the string class is Str. Worry about traps! The object may not have been created! Instead, it might just point to an object that was previously created. Only through the new () method can you guarantee that a new object is created each time. Because of the immutable nature of the string class, you should consider using the StringBuffer class to improve program efficiency when a string variable needs to change its value frequently.


Memory allocation strategy in Java and heap and stack comparison  
2.1 memory allocation policy  
According to the compilation principle, the memory allocation of the program is three strategies, namely static, stack, and heap.  
Static storage allocation is the ability to determine at compile time the storage space requirements for each data target at run time, so that they can be allocated a fixed amount of memory at compile time. This allocation policy requires that the existence of mutable data structures (such as variable groups) not be allowed in the program code, and that nested or recursive structures are not allowed to appear. Because they can cause the compiler to not be able to calculate the exact storage space requirements.  
Stack storage allocation can also be called dynamic storage allocation, which is implemented by a stack-like run stack. Contrary to static storage allocation, in a stacked storage scenario, the requirements for the data area are completely unknown at compile-time. It is only possible to know when running, but when it comes to running a program module, it is necessary to know the size of the data area required by the program module to allocate memory for it. As with the stacks we know in data structures, stack storage allocations are distributed according to 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 compile-time or at runtime module entrances. such as variable-length strings and object instances. The heap consists of large chunks of available or free blocks, and the memory in the heap can be allocated and freed in any order.

2.2 Heap and stack comparison  
The above definition is summarized from the compiling principles of the textbook, in addition to static storage allocation, it is very rigid and difficult to understand, the following aside static storage allocation, centralized comparison heap and stack:  
from the function and function of the heap and stack to 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 of 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, but it is said that although the allocation is performed at the time the program is running, the size of the allocation is determined, unchanged, and this "size" 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 is a certain price to pay: it will take longer to allocate storage space in the heap! This is the reason we have just said that the inefficiency of the reasons, it seems that comrade Lenin said good, people's advantages are often also human shortcomings, people's shortcomings are often human advantages (halo ~).

2.3 Heap and Stack   in the JVM;
The JVM is a stack-based virtual machine. The JVM allocates a stack for each newly created thread. That is, 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 calculations, 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 like this: A 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.

When the JVM runs, it divides the memory into heaps and stacks, and the heap holds the objects created, and when the Java string Object memory is implemented, it opens up a small amount of memory in the heap, called a constant pool of strings, to hold a particular string object.
The two ways to create a string object are different, the first simple syntax without new, i.e.
String s1= "JAVA";
The creation step is to see if there is a string object in the constant pool that is identical to "JAVA", and if so, point S1 to the object, and if not, create a new object and let S1 point to it.
The second type is the new syntax.
String s2= "JAVA";
This syntax is to create the object in the heap instead of in a constant pool, and point S2 to it, and then go to the string constant pool to see if there is an object with the same content, and if so, the new string object is associated with the object in the string constant pool, if not, Creates a string object in the string constant pool that contains the content, and links the objects in the heap memory to the newly created objects in the string constant pool.
This is the one-time input of strings, the memory mechanism of lifetime returns, and the benefits of string comparisons

Heap and Stack 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.