Java heap memory and stack memory details

  • 2020-05-12 02:42:19
  • OfStack

Heap and stack in Java Java divides memory into two types: one is stack memory and one is heap memory. The & # 8203;

Variables of some basic types defined in functions and reference variables of objects are allocated in the stack memory of functions. When a variable is defined in a block of code, java allocates the memory space for the variable in the stack. When the scope of the variable is exceeded, java will automatically free up the memory space allocated for the variable, which can be immediately used for other purposes.

Heap memory is used to hold objects and arrays created by new. Memory allocated in the heap is managed by the java virtual machine automatic garbage collector. In the heap produced after an array or object, you can also define a special variable in the stack, value of this variable is equal to the array or object in the heap memory address, in this particular variable in the stack becomes an array or object reference variables, it can be used in the program after stack memory references in the variable to access in the heap array or object, or as an array or object reference variables 1 individual name, or symbol.

Reference variables are ordinary variables that allocate memory on the stack when defined and are freed when the program runs out of scope. And allocated in the heap array & object itself, even if the program runs to use new generate array and object code block in the locality of the statements, arrays, and the object itself retained heap memory will not be released, arrays and objects in the absence of reference variable pointing to it, to become garbage, can no longer be used, but still account for the memory, in the following an uncertain time released by the garbage collector. This is also the main reason that java takes up more memory. In fact, the variables in the stack refer to the variables in the heap memory. This is the pointer in Java!

The heap and stack in Java

Java divides memory into two types: stack memory and heap memory.

1. The stack (stack) and the heap (heap) are both places where Java stores data in Ram. Unlike C++, Java automatically manages stacks and heaps, and programmers cannot set stacks or heaps directly.

2. The stack has the advantage of being faster to access than the heap, second only to the registers located directly in CPU. However, the disadvantage is that the data size and lifetime in the stack must be fixed and there is no flexibility. In addition, stack data can be Shared. The advantage of the heap is that the memory size can be allocated dynamically and the lifetime does not have to be told to the compiler in advance. The garbage collector of Java will automatically pick up the data that is no longer used. The disadvantage is that access is slow because memory is allocated dynamically at run time.

3. There are two types of data in Java.

One is the basic type (primitive types), and there are eight types: int, short, long, byte, float, double, boolean, char(note,
There is no base type for string). This type is defined by int a = 3; long b = 255 L; The form to be defined is called an automatic variable. It is worth noting that the automatic variable stores a literal value, not an instance of the class, that is, not a reference to the class, where no class exists. int a = 3; So a here is a reference to int,

Point to the literal 3. The values of these literals are known by size and by lifetime (the literals are fixed in a block, and the field values disappear when the block exits),

For the sake of speed, it's in the stack.

In addition, there is a very important particularity of the stack, which is that the data in the stack can be Shared. Suppose we simultaneously define:

int a = 3;
int b = 3;

The compiler first processes int a = 3; It will first create a reference to the a variable in the stack, and then look for an address with a literal value of 3. If it doesn't find it, it will create an address with a literal value of 3, and then point a to the address with a literal value of 3. And then int b = 3; After the b reference variable is created, b is directed to the address of b because it already has the literal 3 in the stack. In this case, both a and b point to 3 at the same time.

In particular, this literal reference is different from a reference to a class object. Assume that references to two class objects point to an object at the same time. If one object reference variable modifies the internal state of the object, the other object reference variable immediately reflects the change. In contrast, changing the value of a literal reference does not cause the value of another reference to that literal to change as well. In the example above, after we have defined the values a and b, we make a=4; So b is not going to be equal to 4, it's going to be equal to 3. Inside the compiler, a=4; , it will research the stack to see if there is a literal value of 4. If not, it will reopen the address to store the value of 4. If it already exists, point a directly to this address. So a change in the value of a does not affect the value of b.

The other is to wrap class data, such as Integer, String, Double, etc., which wrap the corresponding basic data types. All of this class data exists in the heap, and Java USES the new() statement to explicitly tell the compiler that it is created dynamically at run time as needed, so it is flexible, but with the disadvantage that it takes more time.

In JAVA, there are six different places to store data:

1. Register (register). This is the fastest storage area because it is located in a different place from other storage areas -- inside the processor. However, the number of registers is extremely limited, so registers are allocated by the compiler according to requirements. You cannot directly control or sense any sign of register presence in the program.

2. Stack (stack). It is in generic RAM, but can be supported from the processor via its "stack pointer." If the stack pointer moves down, new memory is allocated. If you move up, you free that memory. This is a fast and efficient way to allocate storage, second only to registers. When creating a program, the JAVA compiler must know the exact size and lifetime of the data stored on the stack, because it must generate the code to move the stack pointer up and down. This 1 constraint limits the flexibility of the program, so while some JA VA data is stored on the stack -- specifically object references -- JAVA objects are not stored there.

3. Heap (heap). 1 general memory pool (also present in RAM) for all JAVA objects. The advantage of the heap being different from the stack is that the compiler does not need to know how many storage areas are allocated from the heap or how long the stored data will live in the heap. Therefore, there is a lot of flexibility in allocating storage in the heap. When you need to create an object, you only need new to write 1 simple line of code. When you execute this line of code, it will automatically allocate storage in the heap. Of course, there is code to be paid for this flexibility. Storage allocation with the heap takes more time than storage with the stack.

4. Static storage (static storage). By "static," I mean "in a fixed position." Static storage holds data that was present when the program was running. You can use the keyword static to identify that a particular element of an object is static, but JAVA objects themselves are never stored in a static storage space.

5. Constant storage (constant storage). Constant values are usually stored directly within the program code, which is safe because they will never be changed. Sometimes, in an embedded system, the constant itself is separated from the rest, so in this case, you can choose to put it in ROM

6. Non-RAM storage. If the data exists completely outside of the program, it can exist without any control by the program and even when the program is not running.
In terms of speed, there is the following relationship:

register < The stack < The heap < other

"Thinking in Java"

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 

Variables of some basic types defined in functions and references to objects are allocated in the function's stack memory.

When a variable is defined in a block of code, Java allocates the memory space for the variable in the stack. When the scope of the variable is exceeded, Java will automatically free up the memory space allocated for the variable, which can be immediately used for other purposes.

Heap memory is used to hold objects and arrays created by new.

Memory allocated in the heap is managed by the automatic garbage collector of the Java virtual machine.

After an array or object is generated in the heap, a special variable can be defined in the stack so that the value of the variable in the stack is equal to the first address of the array or object in the heap memory, and the variable in the stack becomes the reference variable of the array or object.

A reference variable is equivalent to a name for an array or object, which can then be used in a program to access an array or object in the heap using a reference variable in the stack.
Specifically, the stack and heap are the places where Java used to store data in Ram. Unlike C++, Java automatically manages stacks and heaps, and programmers cannot set stacks or heaps directly.

Java's heap is an area of runtime data from which the class (object) allocates space. These objects are created by new, newarray, anewarray, and multianewarray instructions, and they do not require program code to be explicitly released. The heap is taken care of by garbage collection. The advantage of the heap is that you can dynamically allocate memory and you don't have to tell the compiler in advance about the lifetime, because it dynamically allocates memory at run time. The Java garbage collector automatically picks up data that is no longer in use. The disadvantage is that access is slow because memory is allocated dynamically at run time.

The advantage of a stack is that access is faster than the heap, second only to registers, 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 no flexibility. The stack mainly contains 1 basic types of variables (,int, short, long, byte, float, double, boolean, char) and object handles.

One of the important peculiarities of the stack is that the data in the stack can be Shared. Suppose we simultaneously define:

int a = 3;
int b = 3;

The compiler processes int a = 3; First it creates a reference to a in the stack, then looks for the value 3 in the stack, if it doesn't find it, stores the 3 in, and then points a to 3. Then int b = 3; After you create the reference variable for b, you point b directly to 3 because you already have the value 3 on the stack. Thus, both a and b point to 3 at the same time. Now, if I take a=4; Then the compiler will research the stack to see if there are 4 values in it. If not, it will store the 4 in the stack and make a point to 4. If you already have one, point a directly to the address. Therefore, a change in the value of a does not affect the value of b. Note that this sharing of data is different from sharing two references to one object at the same time, because in this case the modification of a does not affect b. It is done by the compiler, which helps save space. One object reference variable modifies the internal state of the object, affecting the other object reference variable.

String is a special wrapper for class data. You can use:


String str = new String("abc"); 
String str = "abc"; 

The first USES new() to create the new object, which is stored in the heap. A new object is created every time it is called.
The second is to first create an object reference variable str to String in the stack, and then look for "abc" in the stack. If not, then put "abc" on the stack, and make str point to "abc"; if there is "abc", make str point to "abc".

The equals() method is used to compare the values in the class. When testing whether references to two wrapper classes refer to the same object, use ==, and the following example illustrates the above theory.


String str1 = "abc"; 
String str2 = "abc"; 
System.out.println(str1==str2); //true 

You can see 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 way new is used is to generate different objects. One is generated every time.

Therefore, the second way to create multiple "abc" strings only has one object in memory. This method is beneficial and saves memory space. At the same time, it can improve the running speed of the program to a certain extent, because JVM will automatically decide whether it is necessary to create new objects based on the actual situation of the data in the stack. For String str = new String("abc"); , 1 almost creates a new object in the heap, regardless of whether the string values are the same or whether it is necessary to create a new object, thus increasing the burden on the program.

On the other hand, note that we are using String str = "abc"; When defining a class, it is always taken for granted that the String class object str was created. (not 1, because if there is no previous, then it will be created, this is the creation of the object, if there is the original, then point to the original object is ok)! The object may not have been created! It might just point to an object that has been created previously. Only the new() method guarantees that a new object is created one at a time. Because of the immutable nature of the String class, the StringBuffer class should be considered when the String variable needs to change its value frequently to improve program efficiency.


Related articles: