Java heap memory and stack memory detailed introduction _java

Source: Internet
Author: User
Tags arrays garbage collection wrapper

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

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 Java Virtual Machine automatic garbage collector. After generating an array or object in the heap, you can also define a special variable in the stack that equals 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 a reference variable in the stack memory in your program to access an array or object in the heap, which is equivalent to an alias, or a code name, for an array or object.

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 a Java comparison of the main reason for memory, in fact, the variables in the stack point to the variables in the heap memory, which is the pointer in Java!

Heap and Stack in Java

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

1. Stacks (stack) and heaps (heap) are places where Java is used to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set stacks or heaps.

2. The advantage of the stack is that access 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, stack data can be shared. 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. There are 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,
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,

Point to the literal value of 3. The value of the data, due to the size of the known, lifetime known (these literals are fixed in a program block, the program block exit, the field values disappear),

The reason for the pursuit of speed, is 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:

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.

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

1. Register (Register). This is the fastest store because it is located in a different storage area--within the processor. But the number of registers is extremely limited, so the registers are allocated by the compiler according to the requirements. You can't control it directly, and you can't feel any sign of the register in the program.

2. Stacks (Stack). is located in Universal RAM, but it can be supported from the processor by its stack pointer. If the stack pointer moves downward, the new memory is allocated, and the memory is freed if you move up. This is a fast and efficient method of allocating storage, second only to registers. When you create a program, the Java compiler must know the exact size and lifecycle of all the data stored in the stack, because it must generate the appropriate code to move the stack pointer up and down. This constraint limits the flexibility of the program, so although some ja va data is stored on the stack-especially object references, Java objects do not store them.

3. Heap (heap). A general-purpose memory pool (also in RAM) for storing so Java objects. The advantage of a heap that differs from the stack is that the compiler does not need to know how many storage areas to allocate from the heap or how long the stored data will survive in the heap. Therefore, allocating storage in the heap has great flexibility. When you need to create an object, you just need to write a simple line of code that, when executed, will automatically store allocations in the heap. Of course, for this flexibility, you have to pay the appropriate code. Storing allocations with a heap requires more time than storing storage on a stack.

4. Static storage (storage). The "static" here means "in a fixed position." Data stored in a static store that always exists when the program is running. You can use the keyword static to identify that a particular element of an object is static, but the Java object itself is never stored in a static storage space.

5. Constant storage (constant storage). Constant values are usually stored directly inside the program code, and it is safe to do so because they will never be changed. Sometimes, in an embedded system, the constants themselves are separated from other parts, so in this case, you can choose to place them in ROM

6. Non-RAM storage. If the data is completely alive outside of the program, it can be free of any program control and can exist when the program is not running.
In terms of speed, there are the following relationships:

Registers < Stacks < Heaps < other

"Thinking in Java" from the above passage

Question one:

String str1 = "abc"; 
String str2 = "abc"; 
System.out.println (STR1==STR2); True 

Question two:

String str1 =new string ("abc"); 
String str2 =new string ("abc"); 
System.out.println (STR1==STR2); False 

Question three:

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 

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.
Specifically: stacks and heaps are places where Java is used to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set stacks or heaps.

Java's heap is a run-time data area in which the object allocates 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. The heap is responsible for garbage collection, the advantage of the heap is the dynamic allocation of memory size, the lifetime does not have to tell the compiler in advance, because it is dynamically allocating memory at runtime, the Java garbage collector will automatically take away these no longer used data. The disadvantage is that the access rate is slow 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. The disadvantage is that the data size and lifetime in the stack must be fixed and inflexible. There are some basic types of variables in the stack (, int, short, long, byte, float, double, Boolean, char), and object handles.

Stack has a very important particularity, is the existence of the stack of data can be shared. Let's say we both define:

int a = 3;
int b = 3;

The compiler deals with int a = 3 First, it creates a reference to a in the stack, finds out if there is a 3 value in the stack, and if not, it stores 3 in, then points a to 3. then process int b = 3, after you create the reference variable for B, because you already have 3 in the stack, point B directly to 3. In this way, there is a case where A and B both point to 3. At this point, if you make a=4 again, the compiler will search for a 4 value in the stack, and if not, put 4 in and point A to 4, and if so, direct a to this address. Therefore the change of a value does not affect the value of B. Note that this sharing of data is different from the two-object reference to an object, because the modification of a does not affect B, it is done by the compiler, and it helps save space. While an object reference variable modifies the internal state of the object, it affects another object reference variable.

A string is a special wrapper class data. Can be used:

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

In two forms, the first is to create a new object with new (), which is stored in the heap. Each time a call is made, a new object is created.
And the second is to create an object reference variable str in the stack on a string class, then find out if there is any "ABC" in the stack, and if not, store "ABC" in the Stack and make str point to "ABC", and If "ABC" is already there, direct STR to "ABC".

When comparing the values in a class with the Equals () method, use = = when testing whether references to two wrapper classes are pointing to the same object, use the following example to illustrate the above theory.

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

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

String str1 =new string ("abc"); 
String str2 =new string ("abc"); 
System.out.println (STR1==STR2); False 

The way to new is to generate different objects. Generate one each time.

So the second way to create multiple "ABC" strings is that there is only one object in memory. This formulation 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 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.

On the other hand, note that when we use a format-definition class such as String str = "ABC", we always assume that the object str of the string class was created. (not necessarily, because if not beforehand, then will create, this is to create the object, if there is, then point to the original object on it)! The object may not have been created! Instead, you might just point to an object that you have previously created. Only the new () method can be used to guarantee that one 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 string variables need to change their values frequently.

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.