Java Heap and Stack detailed-latest finishing __java

Source: Internet
Author: User
Tags data structures format definition wrapper


Title:

Some of the basic types of variables and 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 memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically releases the memory space allocated for the variable, which can be used as an immediate alternative.

heap memory is used to store 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 object in the heap, you can also define a special variable in the stack so that the value of the variable in the stack equals the first address of the array or object in the heap memory, and the variable in the stack becomes the reference variable for the array or object. A reference variable is equivalent to a name that is an array or an object, and you can later use the reference variable in the stack to access the array or object in the heap.


A reference variable is a generic variable that allocates memory in the stack when defined, and a reference variable is released outside the program's function. and the array and the object itself are allocated in the heap, even if the program runs to a block of code that uses new to generate arrays and objects, the heap memory occupied by the array and the object itself is not freed, and the array and object are turned into garbage and can no longer be used without reference to the variable, but still occupy memory, is released by the garbage collector at a later uncertain time. This is also the Java comparison of the main reason for memory !

......

Stacks and heaps (heap) are places where Java is used to store data in RAM. The advantage of the stack is that the access rate is faster than the heap, second only to the registers directly located in the CPU. The disadvantage is that the data size and lifetime in the stack must be fixed and inflexible. In addition, the stack data can be shared, as detailed in the 3rd. The advantage of the heap is that the memory size can be dynamically allocated, and that the Java garbage collector automatically collects the data that is no longer in use without having to tell the compiler beforehand. The disadvantage is that the access rate is slow due to the dynamic allocation of memory at run time.


Text:


1. Java in stacks (stack) and heap (heap)

(1) Memory allocation strategy
According to the principle of compiling, there are three kinds of strategies for the memory allocation of program running, which are static, stack type, and heap type.
static storage allocation refers to the need to determine the storage space of each data target at run time at compile time, so that they can be allocated a fixed memory space at compile time. This allocation policy requires that the existence of variable data structures (such as variable groups) is not allowed in program code. Nested or recursive structures are not allowed to appear because they all cause the compiler to not compute the exact storage space requirements.
stack Storage Allocation can also be called dynamic storage allocation, and is implemented by a stack of stacks similar to that of a heap. and static storage allocation in contrast, in the stack storage scenario, the program's requirements for the data area are completely unknown at compile time and can only be known when it is run. However, when entering a program module in operation, it is necessary to know the size of the data area required by the program module to allocate memory for it. Like the stacks we know about in data structures, stack storage allocations are distributed according to advanced principles.


Static storage allocation requires that the storage requirements of all variables be known at compile time, and stack storage allocation requires that all storage requirements be known at the entrance of the process, while the heap storage allocation is dedicated to the inability to determine the memory allocation of the data structure of the storage requirement at compile-time or runtime module entrances. such as variable length strings and object instances. The heap is made up of large chunks of available blocks or free blocks, and the memory in the heap can be allocated and released in any order.


(2) Comparison of Heap and stack
The above definition is summarized from the textbook of compiling principles, in addition to static storage allocation, it appears very inflexible and difficult to understand, the following aside from the static storage allocation, from the heap and stack functions and functions to focus on the stack and stack, stacks are 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/s + +, all method calls are done through stacks, and all local variables, formal parameters, are allocated memory space from the stack. It's not really a distribution, it's just going up from the top of the stack, like a conveyor belt in a factory (conveyor belt), stack pointer will automatically guide you to the place where you put things, All you have to do is just put things down. When you exit the 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 assigning a data area for a program module that is about to be called, Should know the size of the data area in advance, it is said that although the allocation is performed while the program is running, but the size of the allocation is determined, unchanged, and this "size" is determined at compile time, not at runtime.


A heap is an application that requests the operating system to allocate its own memory when it is running, and because of the memory allocations 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 doesn't have to know how much storage to allocate from the heap, It is also not necessary to know how long the stored data will stay in the heap, so it is much more flexible to save the data with the heap. In fact, object-oriented polymorphism, heap memory allocation is essential, because the storage space required for polymorphic variables can only be determined after the object has been created at run time. In C + +, when you want to create an object, you simply use the new command to compile the relevant code. When this code is executed, the data is automatically saved in the heap. Of course, to achieve this flexibility, there is a certain cost: it takes longer to allocate storage space in the heap. This is what led to the inefficiency of what we have just said, it seems that comrade Lenin said good, people are often the advantages of human shortcomings, human shortcomings are often the advantages of people (halo ~).


(3) Heaps and stacks in the JVM
The JVM is a stack based virtual machine. The JVM assigns a stack to each newly created thread. That is, for a Java program, it runs through the operation of the stack. The stack saves the state of the thread in frames. The JVM does only two things on the stack: A frame-by-stack and a stack operation.
We know that a method that a thread is executing is called the current method of this thread. We may not know that the current method uses a frame called the current frame. When a thread activates a Java method, the JVM presses a new frame into the Java stack on the thread. This frame naturally becomes the current frame. During the execution of this method, this frame is used to hold parameters, local variables, intermediate computations, and other data. This frame here is similar to the concept of the activity record in the compiler principle.
From this allocation mechanism in Java, the stack can also be understood: stacks (stack) is the storage area that the operating system establishes for this thread when it establishes a process or a thread (a thread in an operating system that supports multithreading), and the region has an advanced feature.
Each Java application uniquely corresponds to a JVM instance, with each instance uniquely corresponding to a heap. All of the class instances or arrays that the application creates in the run are placed in this heap and are shared by all threads that apply. Unlike C + +, the allocation heap memory in Java is automatically initialized. The storage space for all objects in Java is allocated in the heap, but the reference to this object is allocated in the stack, that is, allocating memory from two places when an object is created, the memory allocated in the heap actually establishes the object, and the memory allocated in the stack is just a pointer to the heap object (reference) Just.

2. Stacks and heaps of advantages

The advantage of the stack is that the access rate is faster than the heap, second only to the registers directly located in the CPU. The disadvantage is that the data size and lifetime in the stack must be fixed and inflexible. In addition, the stack data can be shared, as detailed in the 3rd. The advantage of the heap is that the memory size can be dynamically allocated, and that the Java garbage collector automatically collects the data that is no longer in use without having to tell the compiler beforehand. The disadvantage is that the access rate is slow due to the dynamic allocation of memory at run time.

3. Two types of data in Java

One is the basic type (primitive types), there are 8 kinds, that is, int, short, long, byte, float, double, Boolean, char (note that there is no basic type of string). This type of definition is passed through such as int a = 3; The form of long B = 255L is defined, called an automatic variable. It is worth noting that the automatic variable is a literal value, not an instance of the class, that is, not a reference to a class, where there is no class. such as int a = 3; Here's A is a reference to the int type, pointing to the literal value of 3. These literal data, due to the size of known, lifetime known (these literals are fixed in a program block, the program block exit, the field value disappears), for the pursuit of speed reasons, exist in the stack.

In addition, the stack has a very important particularity, is the existence of the stack of data can be shared. Let's say we both define:
Copy content to Clipboard code:
int a = 3;
int b = 3;
The compiler first deals with int a = 3; First, it creates a reference to a variable in the stack, and then looks for an address with a literal value of 3, then opens an address that holds the face value of 3 and then points a to 3. Then deal with int b = 3, after creating the reference variable for B, the B directly points to the address of 3 because it already has 3 of the literal value on the stack. In this way, there is a case where A and B both point to 3.

It is particularly noteworthy that the reference to this literal is different from the reference to the class object. Assuming that references to two classes of objects also point to an object, if an object reference variable modifies the internal state of the object, then another object reference variable also instantly reflects the change. Conversely, modifying the value of a literal by reference does not result in another change in the value of the reference to that literal. As in the example above, we define the value of a and B and then make a=4; then, b is not equal to 4, or equal to 3. Inside the compiler, when A=4 is encountered, it will search the stack for a 4 literal value, and if not, reopen the address for a value of 4, and if so, point a directly to the address. Therefore the change of a value does not affect the value of B.

The other is wrapping class data, such as Integer, String, and double, which wraps the corresponding basic data types. All of these class data exist in the heap, and Java uses the new () statement to tell the compiler that it is dynamically created at run time, so it is more flexible, but the disadvantage is that it takes more time.

4. String is a special wrapper class data.

That is, you can use string str = new String ("abc"); form, or it can be created in the form of String str = "abc" (In contrast, you have never seen an expression of integer i = 3 before JDK 5.0, because class and literal values are not can be generic except for string. In JDK 5.0, this expression is possible. Because the compiler is in the background for the integer i = new Integer (3) conversion). The former is the process of creating a canonical class, in Java, where everything is an object, and an object is an instance of a class, all created in the form of new ().

Some classes in Java, such as the DateFormat class, can return a newly created class through the getinstance () method of the class, which seems to violate this principle. Fact The class uses a singleton pattern to return an instance of a class, except that the instance is created inside the class through new (), and getinstance () hides this detail externally. So why is it a violation of the above principle to create an instance in string str = "abc" and not through new (). No, actually.

5. Internal work on string str = "abc" . Inside Java, this statement is translated into the following steps:

(1) First define an object reference variable named str to the String class: String str;

(2) in the stack to find there is no store value of "ABC" address, if not, create an address that holds the value of "ABC", then creates an object o of the new string class, points to the address of the string value of O, and notes the object o of the reference next to this address in the stack. If you already have an address with the value "ABC", look for the object o and return the address of O.

(3) Point Str to the address of object o.
It is noteworthy that the string values in the generic string class are stored directly. But like string str = "abc"; in this case, its string value holds a reference to the data in the existing stack.

To better illustrate this issue, we can verify this by using several of the following code.

String str1 = "abc"; 
String str2 = "abc"; 


Note that we do not use Str1.equals (STR2) in this way, because this compares the values of two strings to be equal. The = = number, as described in the JDK, returns the true value only if two references are pointing to the same object. And what we're looking at here is whether str1 and str2 all point to the same object.
As a result, the JVM created two references str1 and str2, but only one object was created, and two references all pointed to the object.


Let's go further and change the above code to:

String str1 = "abc"; 
String str2 = "abc"; 
str1 = "BCD"; 
System.out.println (str1 + "," + str2); BCD, ABC 
System.out.println (STR1==STR2);//false


This means that the change in assignment results in a change in the reference of the class object, and str1 points to another new object. And str2 still points to the original object. In the example above, when we change the value of str1 to "BCD", the JVM discovers that there is no address in the stack that holds the value, opens up the address, and creates a new object whose string value points to the address.

In fact, the string class is designed to be an immutable (immutable) class. If you want to change its value, you can, but the JVM silently creates a new object at run time based on the new value, and then returns the address of the object to the reference of the original class. This creation process is completely automated, but it takes up more time after all. In the environment that is sensitive to the time requirement, it will have a certain adverse effect.

Then modify the original code:

String str1 = "abc"; 
String str2 = "abc"; 

str1 = "BCD"; 

String STR3 = str1; 
System.out.println (STR3); BCD 

String STR4 = "BCD"; 
System.out.println (str1 = = STR4); True


Str3 This object's reference directly points to the object that str1 points to (note that STR3 does not create a new object). When STR1 has finished changing its value, it creates a reference str4 for string and points to a new object created by str1 modifying the value. It can be found that this time STR4 also did not create a new object, so as to realize the stack of data sharing.

Let's look at the following code again.

String str1 = new String ("abc"); 
String str2 = "abc"; 
System.out.println (STR1==STR2); False two references were created. Two objects were created. Two references point to different two objects. 

String str1 = "abc"; 
String str2 = new String ("abc"); 
System.out.println (STR1==STR2); False two references were created. Two objects were created. Two references point to different two objects.


The above two pieces of code show that as long as the new object is created with new (), it is built in the heap and its string is stored separately, even if it is the same as the data in the stack, and is not shared with the data in the stack.

6. The value of the data type wrapper class cannot be modified . Not only the value of the string class is not modifiable, all data type wrapper classes cannot change their internal values.


7. Conclusions AND recommendations:

(1) When we use a format definition class such as String str = "ABC", We always think of course that we created the object str of the String class. Worry about traps. The object may not have been created. The only certainty is that a reference to the string class was created. Whether or not this reference is pointing to a new object must be considered in context, unless you are creating a new object by means of the new () method. So it's more accurate to say that we created a reference variable str that points to the object of the string class, which refers to a string class with a value of "ABC". Waking up to this point is helpful in troubleshooting bugs that are hard to find in the program.

(2) The use of string str = "ABC" can improve the speed of the program to some extent, because the JVM automatically determines whether it is necessary to create a new object based on the actual situation of the data in the stack. For code with string str = new String ("abc"), the new object is created in the heap, regardless of whether its string value is equal or not, and it is necessary to create a new object, which increases the burden on the program. This thought should be the idea of the meta pattern, but it is not known whether the JDK's internal implementation of this pattern is applied here.

(3) When comparing the values within the wrapper class, use the Equals () method, or = = when the reference to the two wrapper class is pointing to the same object.

(4) Because of the immutable nature of the string class, when a string variable needs to change its value frequently, consideration should be given to using the StringBuffer class to improve program efficiency.


Article Data reference from:

http://blog.csdn.net/shimiso/article/details/8601523

http://bbs.csdn.net/topics/290004554

Http://blog.sina.com.cn/s/blog_65ca444f01011q14.html

Http://www.cnblogs.com/whgw/archive/2011/09/29/2194997.html





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.