Java Memory mechanism (heap and stack), memory address

Source: Internet
Author: User
Tags data structures garbage collection wrapper

Introduction of the problem:

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

Because the above problem makes me ambiguous, so I specially collected some information about the Java memory allocation, the following is the net pick:

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 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.

In particular, say:
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";
System.out.println (STR1==STR2); True
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. Worry about traps. 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.


Memory allocation strategy in Java and comparison of Heap and stack
2.1 Memory allocation policy
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 for each data target at run time at compile time, as a result, they can be allocated a fixed memory space at compile time. This allocation policy requires that variable data structures (such as variable groups) are not allowed in the program code, and that nested or recursive structures are not allowed to appear. Because they all cause the compiler to not compute the exact storage space requirements.
Stack-type storage allocation, also known as dynamic storage allocation, is implemented by a stack of stacks. In contrast to static storage allocation, in a stack storage scenario, the requirements of a program for the data area are completely unknown at compile time, only to be known at runtime, but when running into a program module, You must 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 the advanced principle.
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.2 Stack and Stack comparisons
The above definition is summarized from the textbook of compiling principles, except for static storage allocation, it appears very stiff and difficult to understand, the following aside from static storage allocation, concentrated comparison heap and stack:
From the stack and stack function and function 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/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 ~).

2.3 The heap and stack 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.

When the JVM runs, it divides memory into heaps and stacks, where the objects are created, Java string Object memory is implemented, and a small memory is opened in the heap, called a string constant pool, to hold a particular string object.
There are two different ways to create a string object, the first of which is a simple syntax without new
String s1= "JAVA";
The creation step is to see if there is a string object in the constant pool that is not the same as "JAVA", and if so, to point S1 to the object, and if not, create a new object and have the S1 point to it.
The second is the new syntax
String s2= "JAVA";
This syntax creates an object in a heap rather than in a constant pool. and point the 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, connect the new string object to the object in the string constant pool, if not, , a string object containing the content is created in the string constant pool, and the object in the heap memory is associated with the newly created object in the string constant pool.
This is an input to the string, the memory mechanism of lifetime return, which benefits the comparison of strings.

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.