Java Memory Allocation and Management Summary and java memory allocation Summary

Source: Internet
Author: User

Java Memory Allocation and Management Summary and java memory allocation Summary

I want to write this summary for a month, but I still feel that I have almost nothing to write.

I 've been fighting for the last two days. I decided to write out the materials and notes I checked earlier.

If you are familiar with answering a few questions, please let me know. As in the past, I am a minor dish. This article is a summary of the minor class.

First, there are several conceptual issues:

  • What types of runtime memory structures are available in Java?
  • Why is stack separation designed in Java?
  • In Java multithreading, how does one share data?
  • What is the basis of Java reflection?

Then the application layer:

  • What is the difference between referenced type variables and objects?
  • When are local variables and member variables used?
  • How to initialize an array? How to allocate memory when declaring an array?
  • Declare an array of Basic Types and an array of reference types. What is the memory allocation mechanism during initialization?
  • Under what circumstances is our method designed to be static and why? (The last time Mr. Hu asked Wenqi, he was speechless and wanted to answer the question, but he still felt unclear. Here is a brief description)

Well, if you can see the answer at a glance, there is no need to waste your precious time.

If you still do not understand, please follow me along the way.

Java runtime Memory Structure

1.1 Method Area:

The method area is a logical area of memory allocated by the system. It is used to store type information (Class description information) When JVM loads class files ). 

The information stored in the method area includes:

1.1.1Basic information of the class:

Fully qualified names of each class

1.1.2Detailed information of mounted classes:

Therefore, we can understand the basis of reflection.:

When a Class is loaded, all information in the Method Area will be added to form an instance of the Class, representing the loaded Class. All information in the method area can be obtained through reflection of this Class object. We know that an object is a class instance, and a class is an abstraction of objects of the same structure. Objects of the same type actually have the same structure (attributes) and have the same functions (methods). The difference between objects lies only in the difference of attribute values.
Similarly, all our classes are actually Class instances. They all have the same structure-Field array and Method array. The attribute in each class is a specific attribute value of the Field attribute, and the Method is a specific attribute value of the Method attribute.

During runtime, JVM obtains the symbolic reference from the constant pool, parses it into the actual address of the reference item at runtime, and finally uses the fully qualified name, method, and field descriptor in the constant pool, associate the code in the current class or interface with the code in other classes or interfaces.

1.2 Java stack

The JVM stack is the unit for running the program. It determines how the program is executed or how the data is processed.

In Java, a thread has a JVM stack corresponding to the thread, because the thread execution logic is obviously different, therefore, an independent JVM stack is required to store the execution logic of the thread.

Call method:

Java stack memory, which stores the call status of local methods in the form of frames, including parameters, local variables, and intermediate results of method calls (methods are stored in the Method Area in the form of method frames ), every time a method is called, The Method Frame of the method should be pushed to the Java stack to become the current method frame. When the call ends (return), the frame is displayed.

This means:

Some basic types of variables and referenced variables defined in the method are allocated in the stack memory of the method.When a variable is defined in a block of code, Java allocates memory space for the variable in the stack. When the scope of the variable is exceeded (after the method is executed ), java will automatically release the memory space allocated for the variable, and the memory space can be immediately used as another. --------At the same time, because the variable is released, the object corresponding to the variable will lose reference and become garbage that can be recycled by the gc object.

Therefore, we can know the differences between member variables and local variables:

Local variables are declared inside the method. When the method is completed, the memory is released.
Member variable, as long as the object is still there, even if a method is running out, it still exists.
From the perspective of the system, declaring local variables is conducive to more efficient use of memory space (recovery after the method is run ).
Member variables can be used for data sharing between methods.

Java stack memory composition:

The local variable area, the operand stack, and the frame data area.
(1): The local variable area is an array in words. Each array element corresponds to the value of a local variable. When a method is called, local variables of the method are grouped into an array and accessed through indexes. If it is a non-static method, add an implicit reference parameter this, which points to the object that calls this method. The static method does not have the this parameter. Therefore, the object cannot call static methods.

 As a result, we can know when the method is designed as static and when it is not static? 

As mentioned above, an object is an instance of a class. Each object has the same structure but has different attributes.
Static methods cannot be called by objects.
Therefore, static methods are suitable for tool methods in tool classes. These classes are only used to implement some functions and do not need to generate objects. Different individuals can be obtained by setting object attributes.

(2): the operand stack is also an array, but accessed through stack operations. The so-called operands are the data operated by commands. When you need to operate on parameters such as a = B + c, the parameter to be operated will be pushed to the stack, such as B and c, and then the Operation Command will pop up them, and perform the operation. The virtual machine uses the operand stack as the workspace.

(3): constant pool resolution and Exception Handling in frame data zone Processing

1.3 java heap

A java heap is a runtime data zone used to store data units. It stores newly created objects and arrays with the new Keyword, and allocates memory to the objects.

Objects declared in the stack cannot be directly accessed and must be called by pointing to the referenced variable declared in the stack. The referenced variable is equivalent to an array or an object name. Later, you can use the referenced variable in the stack in the program to access the array or object in the heap.

From this we can know the difference between the referenced type variable and the object: 

Declared objects are initialized in the heap memory and are actually used to store data. Cannot be accessed directly.

The reference type variable is saved in the stack. It is a symbol (pointer) used to reference objects in the stack ).

Comparison Between Stack and stack:

JAVA stacks and stacks are used to store data. What is the difference between them? Since stacks can also store data, why do we need to design stacks?

1. Data Storage:

We have already noted that:

The stack stores basic or referenced variables.

Objects or array objects are stored in the heap.

In the stack, the reference variable size is 32 bits and the basic type is 1-8 bytes.

However, the object size and array size are dynamic, which also determines the dynamic nature of the data in the heap, because it dynamically allocates memory at runtime, the lifetime does not need to be determined during compilation. the Java Garbage Collector automatically collects the data that is no longer used.

2.Data sharing:

1) data in a single thread class can be shared

For example, we define:

Java code
  1. Int a = 3;
  2. Int B = 3;

The compiler first processes int a = 3. First, it creates a reference with the variable a in the stack, and then finds whether the value 3 in the stack exists. If no value is found, store 3 and point a to 3. Then process int B = 3. After the referenced variable of B is created, B is directed to 3 because there is already 3 in the stack. In this way, both a and B point to 3 at the same time.

If we define:

Java code
  1. Integer a = new Integer (3); // (1)
  2. Integer B = new Integer (3); // (2)

At this time, the execution process is as follows: During execution (1), first create a variable a in the stack, and then instantiate an object in the heap memory, and point variable a to the instantiated object. During execution (2), the process is similar. In this case, there are two Integer objects in the heap memory.

2 ).Data sharing between various threads of a process is implemented through heap.

For example, how can we achieve data sharing in multi-thread development?

The data in the heap is shared by all the thread stacks. We can pass the data in a heap to the working memory of each stack through parameter transmission to achieve data sharing among multiple threads.

(Data sharing between multiple processes must be transmitted over the network .)

3. From the perspective of programming:

From the perspective of software design, the JVM stack represents the processing logic, while the JVM stack represents the data. This separation makes the processing logic clearer. Divide and conquer. This idea of isolation and modularization is embodied in all aspects of software design.

4. Truth of value transfer and reference Transfer

With the above knowledge about stack and stack, we can easily know the truth about value transfer and reference transfer:

1. The program is always running in the JVM stack. Therefore, when passing parameters, there is only a problem of passing basic types and object references. The object itself is not directly transmitted.

But what is the illusion of transferring references?

In running the JVM stack, the basic type and reference processing are the same and both are passed values. Therefore, if the reference method is called, it can also be understood as the call to transfer the reference value, that is, the reference processing is exactly the same as the basic type.

However, when a method is called, The referenced value passed is interpreted (or searched) by the program to the object in the JVM heap, which corresponds to the real object.

If the modification is made at this time, the corresponding object is modified instead of the reference itself, that is, the data in the JVM heap is modified. Therefore, this modification can be maintained.

Finally:

In a sense, objects are composed of basic types.

You can view an object as a tree. If the object's attribute is still an object, it is still a tree (that is, a non-leaf node). The basic type is the leaf node of the tree. When passing program parameters, the passed value itself cannot be modified. However, if the value is a non-leaf node (that is, an object reference ), you can modify all the content under this node.

 In fact, there is no difference between an object-oriented program and a previously structured program in execution..

The introduction of object-oriented only changes the way we think about problems, and is closer to the natural way of thinking.

When we take the object apart, in fact, the object's attribute is data, stored in the JVM heap; and the object's behavior (method) is the running logic, placed in the JVM stack. When writing objects, we actually write the data structure and the data processing logic.

P.S

For Array Memory Allocation and Object-initiated memory allocation issues, please write another topic next time due to space issues.

I have been facing this article for several consecutive days and nights. I want to vomit. come here first.


How to use java for dynamic memory allocation

Dynamic java memory allocation?
In the memory area of the Java virtual machine, the object memory is allocated in the Java Virtual Machine.
That is to say, you can simply create an object in java and do not need to release it.
There are garbage collection in the Virtual Machine. Garbage collection is divided into full gc and common gc. For details, please check the information.
Java helps you complete these tedious processes and accelerate your development process.
We recommend that you use C ++ and understand the principle of placement new.

Memory Allocation in java

1. String is not a basic data type in JAVA. It is actually a class type. For String type data, use = to compare their addresses in the memory. You can regard the data defined by String in JAVA as a pool in the memory. "123" is created in this pool. The next time B = 123, because the pool has 123, JAVA will not create 123 instances, but directly reference B to 123. therefore, the address of a and B is the same, that is, the address of 123 in the memory. Therefore, the value of boolean c = (a = B) is true.
2. There is no "pointer" concept in JAVA, and "pointer" is in C.
3. The instance for creating objects in JAVA is created on the heap and there is no error. For example:
Public class {
Void set (){
......}
Public static void main (String [] args ){
A a = new ();
}
}
Here there is A class A, new A () is an instantiation of the class. An instance of Class A is created on the stack, and a A is A class object, A a = new A (); refers to referencing class objects to class instances. You can find that the new A (); statement can be run in the program. Therefore, instances of classes do not always depend on class objects.

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.