Java memory mechanism (heap and stack), memory address

Source: Internet
Author: User

Problem introduction:

Question 1:

String str1 = "ABC ";
String str2 = "ABC ";
System. Out. println (str1 = str2); // true

Question 2:

String str1 = new string ("ABC ");
String str2 = new string ("ABC ");
System. Out. println (str1 = str2); // false

Question 3:

String S1 = "Ja ";
String S2 = "va ";
String S3 = "Java ";
String S4 = S1 + S2;
System. Out. println (S3 = S4); // false
System. Out. println (s3.equals (S4); // true

As the above problems made me vague, I specially collected some information about Java memory allocation. The following is an example:

Heap and stack in Java
Java divides memory into two types: stack memory and stack memory.

Variables of some basic types defined in the function and referenced variables of the object are allocated in the function stack memory.

When a variable is defined in a code block, Java allocates memory space for the variable in the stack. When the scope of the variable is exceeded, java will automatically release the memory space allocated for the variable, and the memory space can be used for another use immediately.

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's automatic garbage collector.

After an array or object is generated in the heap, you can define a special variable in the stack so that the value of this variable in the stack is equal to the first address of the array or object in the heap memory, the variable in the stack becomes the referenced variable of the array or object.

The referenced variable is equivalent to an array or an object name. Later, you can use the referenced variable in the stack in the program to access the array or object in the heap.

Specifically:
Both stacks and stacks are places where Java is used to store data in Ram. Unlike C ++, Java automatically manages stacks and stacks, and programmers cannot directly set stacks or stacks.
The Java heap is a runtime data zone and class (the object allocates space from it. These objects are created using commands such as new, newarray, anewarray, and multianewarray. They do not need program code to be explicitly released. The heap is responsible for garbage collection. The advantage of the heap is that the memory size can be dynamically allocated, and the lifetime does not have to be told in advance because the heap dynamically allocates memory at runtime, the Java Garbage Collector automatically collects the unused data. However, the slow access speed is due to the need to dynamically allocate memory during runtime.
The advantage of stack is that the access speed is faster than that of stack, second only to register, and stack data can be shared. However, the disadvantage is that the data size and lifetime in the stack must be fixed, and there is a lack of flexibility. The stack mainly stores some basic types of variables (, Int, short, long, byte, float, double, Boolean, char) and object handles.
A very important feature of stacks is that data in stacks can be shared. Suppose we define both:
Int A = 3;
Int B = 3;
The compiler first processes int A = 3. First, it creates a reference with the variable A in the stack, and then finds whether the value 3 in the stack exists. If no value is found, store 3 and 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.

String is a special packaging data. Available:
String STR = new string ("ABC ");
String STR = "ABC ";
The first method is to use new () to create an object, which is stored in the heap. Each call creates a new object.
The second is to first create a string class object in the stack to reference the variable STR, and then find whether the stack contains "ABC". If not, store "ABC" into the stack and point STR to "ABC". If "ABC" already exists, direct STR to "ABC ".

Use the equals () method to compare the values in a class. Use the = method to test whether the references of the two classes point to the same object. The example below illustrates the above theory.
String str1 = "ABC ";
String str2 = "ABC ";
System. Out. println (str1 = str2); // true
It can be seen that str1 and str2 point to the same object.

String str1 = new string ("ABC ");
String str2 = new string ("ABC ");
System. Out. println (str1 = str2); // false
The new method is used to generate different objects. Each time one is generated.
Therefore, the second method is used to create multiple "ABC" strings, and only one object exists in the memory. this method is advantageous and saves memory space. at the same time, it can improve the program running speed to a certain extent, because the JVM will automatically decide whether to create a new object based on the actual situation of the data in the stack. For the code of string STR = new string ("ABC");, a new object is created in the heap, regardless of whether the string value is equal, whether it is necessary to create a new object, this increases the burden on the program.
On the other hand, NOTE: When we define classes using formats such as string STR = "ABC";, we always take it for granted that the STR object of the string class is created. Worry trap! The object may not be created! Instead, it may only point to a previously created object. Only by using the new () method can a new object be created every time. Because of the immutable property of the string class, when the string variable needs to change its value frequently, you should consider using the stringbuffer class to improve program efficiency.

Comparison of memory allocation policies and heap and stack in Java
2.1 Memory Allocation Policy
According to the compilation principle, there are three policies for memory allocation during program running: static, stack, and heap.
Static Storage Allocation refers to the ability to determine the storage space requirements of each data target at runtime during compilation. Therefore, a fixed memory space can be allocated to each data target during compilation. this allocation policy requires that the existence of a variable data structure (such as a variable array) or nested or recursive structure is not allowed in the program code, because they both cause compilation programs to fail to calculate accurate storage space requirements.
Stack-based storage allocation, also known as dynamic storage allocation, is implemented by a stack-like running stack. in contrast to static storage allocation, in stack-based storage solutions, the program's requirements for data areas are completely unknown during compilation and can only be known at runtime, however, when entering a program module during 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.
Static storage allocation requires that the storage requirements of all variables be known during compilation, and stack-based storage allocation requires that all storage requirements be known at the entrance of the process, heap Storage allocation is specifically responsible for the memory allocation of data structures that cannot be determined at the module entrance during compilation or runtime, 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.

Comparison between 2.2 heap and stack
The above definition is summarized in the textbook on compilation principles. In addition to static storage allocation, all of them seem dull and hard to understand. The following describes static storage allocation and how to compare stacks and stacks in a centralized manner:
Compared with the functions and functions of stacks, stacks are mainly used to store objects and stacks are mainly used to execute programs. this difference is mainly determined by the features of the stack and stack:
In programming, for example, in C/C ++, all method calls are performed through stacks, and all local variables and formal parameters are allocated memory space from stacks. In fact, there is no allocation, just use it from the top of the stack, just like a conveyor belt in the factory (Conveyor Belt), stack pointer will automatically guide you to the place where you put things, all you have to do is put things down. when you exit the function, you can modify the stack pointer to destroy the stack content. this mode is the fastest, of course, used to run the program. it should be noted that, during the allocation, for example, when assigning a data zone to a program module to be called, the size of the Data zone should be known in advance, that is to say, although the allocation is performed while the program is running, the size of the allocation is fixed, and the "size" is determined during compilation, not at runtime.
Heap requests the operating system to allocate memory when the application is running. Because the memory allocated is managed by the operating system, it takes time to allocate and destroy the heap, therefore, the efficiency of using the heap is very low. however, the advantage of heap is that the compiler does not have to know how much storage space is allocated from the heap or how long the stored data will stay in the heap. Therefore, storing data in a heap gives you more flexibility. In fact, heap memory allocation is essential for object-oriented polymorphism, because the storage space required for Polymorphism variables can be determined only after the object is created at runtime. in C ++, when creating an object, you only need to use the new command to compile the relevant code. When the code is executed, data is automatically saved in the heap. of course, to achieve this flexibility, you must pay a certain price: It will take longer to allocate storage space in the heap! This is exactly the reason why we have just said that the efficiency is low. It seems that comrade Lenin is good at saying that the advantages of people are also the disadvantages of people, the disadvantage of a person is often the advantage of a person (dizzy ~).

2.3 heap and stack in JVM
JVM is a stack-based Virtual Machine. JVM allocates a stack for each newly created thread. That is to say, for a Java program, its operation is done 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.
We know that the method being executed by a thread 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, JVM will press a new frame into the thread's java stack. This frame naturally becomes the current frame. during the execution of this method, this frame will be used to save parameters, local variables, intermediate calculation processes, and other data. this frame is similar to the activity record concept in the compilation principle.
From the perspective of Java's allocation mechanism, the stack can be understood as follows: a stack is a process or thread created by the operating system (a thread in an operating system that supports multithreading) the storage area created for this thread has the advanced and later features.
Each Java application corresponds to only one JVM instance, and each instance corresponds to only one heap. All the class instances or arrays created by the application during running are stored in this heap and shared by all the threads of the application. unlike C/C ++, heap memory allocation in Java is automatically initialized. In Java, the storage space of all objects is allocated in the heap, but the reference of this object is allocated in the stack. That is to say, the memory is allocated from both places when an object is created, the memory allocated in the heap actually creates this object, and the memory allocated in the stack is just a pointer (reference) pointing to this heap object.

 

During JVM running, the memory is divided into heap and stack. The heap stores the created objects. When implementing the memory of Java string objects, a very small memory is opened in the heap, it is called the String constant pool to store specific string objects.
The two methods for creating a String object are different. The first method does not use the new simple syntax, that is
String S1 = "Java ";
The creation step is to first check whether there are any string objects identical to "Java" in the constant pool. If so, point S1 to this object. If not, create a new object and let S1 point to it.
The second is the new syntax.
String S2 = "Java ";
This syntax creates an object in the heap instead of in the constant pool, points S2 to it, and then goes to the String constant pool to see if there is an object with the same content. If yes, associate the New String object with the object in the String constant pool. If no, create another string object containing the content in the String constant pool, and associate the objects in the heap memory with the objects created in the String constant pool.
This is the memory mechanism for string input and lifetime return, which brings benefits to string comparison.

 

From: http://blog.csdn.net/xyz1982510/archive/2008/09/12/2916467.aspx

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.