Java Program Memory Analysis

Source: Internet
Author: User

Transferred from: http://www.iteye.com/topic/528230


Java program memory is mainly divided into 2 parts, including stack segment (stack memory area), heapsegment (heap memory area).

In analyzing the memory allocation of Java programs, let's start with a frequently used example.


What does the following program print?

New String ("abc"new string("ABC"); System.  out // 1 System.  out // 2

Maybe we have an answer in the heart, the 1th statement prints true, the second statement prints false, yes, as you can imagine, the printing results are like this. So, do you know why the 2nd statement prints false?

Let's take a look at how the data in this program is allocated in memory.

First, we parse the first statement string S1=new string ("abc");
In fact, this statement is the abbreviation for the following two statements,
String S1; 1
S1=new String ("abc"); 2

1. Define a pair-like reference variable named S1 to the string class in the stack memory
2. A space is opened in the heap memory to hold the string "ABC", and the reference variable defined by the 1 S1 points to that space.
Similarly, the second statement, string s2=new string ("abc"), also does the same thing, defines the reference variable, pointing to the newly opened space. Speaking of which everyone may have the answer in mind, why S1!=S2? Because they point to two different heap memory spaces.

In fact, in Java, the new procedure allocates memory is similar to the above, first define the reference in the stack memory, then open up space in the heap memory, store the data, finally let the reference point to the space, if a reference does not point to any space, then when using this reference variable, The program will throw the famous nullpointerexception, in fact, from the name of the exception we can clearly know the cause of the exception, is not it?

======================================================

Familiar with the above example, basically everyone on the Java program memory allocation situation has been introduced, let's go to the next step.
We define one of the following classes:

 Public class   Cat {  privatedouble  weight;    privateint age ;   public Cat (doubleint  _age) {       this. Weight= _ Weight;          this. Age = _age; }     //}

We may have a new cat in other programs, like this:

 Public class demo{     publicstaticvoid  main (string[] args) {         Cat kitty=  New Cat (3.0,2);}     }

So how does this new process proceed?

According to the above analysis of the string type new, you might think, this simple, first define the reference variable in the stack memory kitty, and then allocate a piece of space in the heap memory, the kitty Cat's properties to store in, and finally let the reference variable point to this space, finished.


Yes, the analysis is generally correct, but everyone seems to have overlooked an important detail of how Kitty Cat's properties are stored in the heap memory space?

Let's take a look at the Cat class constructor, which defines two parameters, that is, local variables, when we try to pass a parameter value to it by new, we define two reference variables in the stack memory, _weight,_age and assign values, That is, two reference variables in the stack memory content of 3.0, 2, while in the heap opened a new space, the space has two memory areas, and in-memory content is the system initialization content. The stack's in-memory values are then assigned to the heap-in-memory value by the constructor, so that the new space in the heap is assigned, and then, as you might think, the reference kitty points to the new space. You might think, what about the two pieces of memory allocated in the stack?
In fact, after doing the above things, the local variables will be popped from the stack, the process is spontaneous, it is different from the JVM garbage collection, the JVM garbage collection is mainly used to free up the heap memory space, a block of the existence of not referenced, or reference to its variables will not be used to be recycled.

Oh, very long analysis Ah, I do not know how they look, let's continue.

Suppose there is a method in the demo class, like this:

 Public void Change (Cat _cat) {_cat.setage (5);}

So just put the new kitty in the method, like this:

Newnew Cat (3.0,2);d emo.change (Kitty); System. out. Print (Kitty.getage ());

The program will print the age of Kitty, then will the age change?

You may be affected by a well-known problem in C, that is, the swap (see below), and come to the conclusion that will print 2, but that is not the case and the program will print 5, so what happened? Let's explain this phenomenon by changing the memory of the program.
First, as we analyzed earlier, when new comes out of the Kitty cat, a reference is defined in the stack memory that points to the allocated memory in the heap, and the heap memory holds the kitty cat's information.
Then we start calling the change method, and when we pass kitty to the method, we define the local variable _cat in the stack memory, which will be pointed to the heap memory area that kitty points to, and then _cat the contents of the heap memory area that it points to. Isn't that what Kitty is talking about? The memory area of the heap is changed? Because they point to the same heap of memory. In this way, when you call Kitty.getage (), you get 5 of these results. Finally, the assigned _cat will pop up from the stack.

Analysis here, we look back, swap (swap) problem
We all know there's a way in C that looks like this:

void swap (intint  b) {    intA;     int b;     int temp;}

Then use it in the main function, like this:

int 2 ; int 5 ; swap (A, b);

We all know that it is impossible to exchange the value of a A, but do you still remember the solution, how to solve the problem? In the C language we use pointers, like this:

void swap (intint *a) {     int temp = *A;      *a = *b;      *b = temp;} main () {     int2;      int 5 ;     Swap (&a, &B); }

As you can see here, it's possible to remember that the reference is used here.

Speaking of which, people are not enlightened, in the Java stack memory is a reference Ah, so Java although there is no explicit pointer, but everywhere is the pointer.


====================================================================
All right, take a break, we'll go on.

With a step-by-step, you may have a general understanding of the memory allocation of Java programs, so let's talk about more advanced topics.
At the beginning of the article we use the String class example, do you feel a bit awkward? Yes, maybe everyone defines a string that is directly defined as follows, but what's the difference?

" ABC "  "ABC"; System.  out // 1 System.  out // 2

Obviously, the above program 1th print the statement, the output is true, then the second one?

If you run the program, the 2nd print is also true, why? Are you a little confused, OK, let's analyze the memory allocation of this program.

Here we first introduce a high-level concept: constant Pool
The JVM virtual machine maintains a constant pool for each mounted type. A constant pool is an ordered set of constants used by that type, including direct constants (String,integer and floating point constants), and symbolic references to other types, fields, and methods. For a string constant, its value is in a constant pool. The Chang in the JVM exists as a table in memory, and for string types there is a fixed-length constant_string_info table for storing literal string values, note that the table stores only literal string values and does not store symbol references. In this case, there should be a clearer understanding of where the string values in the constant pool should be stored.
After introducing the concept of the JVM constant pool, we then talk about the location of the memory distribution where the value of "ABC" was mentioned earlier. The value of "ABC", in fact, is that the string "ABC" has been allocated space in the Constant_string_info table of the constant pool to store the value "ABC" when the class file is loaded into memory by the JVM. Since the string constant of "abc" is stored in a constant pool, the constant pool is part of the type information, and the type information is each of the types being reproduced, which is reflected in the JVM memory model that corresponds to the method area that exists in the JVM memory model. That is, the Chang in this type of information is present in the method area, and the method area can be freely allocated in a heap.
This also explains why S1==s2, because they both point to a reference to the "ABC" string in the constant pool, and the new string, as mentioned in the beginning of the article, is "ABC" in the newly allocated heap memory, just a copy of the "ABC" string in the constant pool. Therefore, please do not use the new method to initialize the string type, directly assigned to the value.

OK, first of all, I hope that through this article we have some knowledge of Java program memory.

Java Program Memory Analysis

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.