Java runtime, various types of storage introduction

Source: Internet
Author: User
Tags modifiers thread class

memory allocation in Java  Java Program runtime memory structure is divided into: Method area, stack memory, heap memory, the local method stack several. The  method area holds the loaded class data information, including: basic information: The fully qualified name of each class, the fully qualified name of the direct superclass of each class, whether the class is a class or an interface, the type's access modifier, and an ordered list of the fully qualified names of the direct hyper-interfaces. Details of each loaded class: Run a constant pool, field information, method information, static variables, references to class ClassLoader, and references to class classes.
Stack Memory The Java stack memory consists of a local variable area, an operand stack, a frame data area, and a frame that holds the call state of the local method (including the parameters of the method call, local variables, intermediate results ...). )。
Heap Memory heap memory is used to hold objects and arrays created by new. The memory allocated in the heap is managed by the automatic garbage collector of the Java Virtual machine.
local method Stack memory Java uses Java local interface JNI (Java Native Interface) to invoke programs written in other languages, and in Java, Native modifiers are used to describe a method that is a local method Java object creating memory

In Java, memory consists mainly of 4 blocks, heap memory, stack (stack memory), data segment (static variable or constant store), Codesegment (method area).
The heap memory holds the new object, and the new object contains only the member variables.
Stack in memory: The local member variable is stored. For basic data types, the value of the underlying variable is stored, and for the object variable, the address of the heap memory is stored.
Static, constant area: A static variable (class variable) or constant is stored.
Method Area: The method in which the object is stored. So even if new has multiple objects there is only one method.

Such as
A = new A (); A contains a work method with 2 member variables, a, a, a, B. Then the corresponding memory allocation is
Then a is allocated in the stack memory. It contains an address that points to the new A () stored in the heap memory.
New A () causes a chunk of space to be allocated in the heap memory, where the A object contains both A and B.
The work () method allocates memory in the Codesegment area.
If a B = A at this point, then the value of a is copied to B, that is, the value of B is the address saved in a
*************************************************************************************************************** ***********
*************************************************************************************************************** ***********

This is an article about the structure of Java memory organization, the concepts involved are mainly the method area, Java stack, Java heap. With this article, you can deepen your understanding of Java objects and optimize the structure of your code.

Begin:

Want to write this summary brewing has a month, but always feel almost something, has not dared to pen.

The last two days of fighting overnight, re-collation of the previous information, notes, or decided to write it out.

Now put forward a few questions, if you can be proficient in the answer to the prawn, please drift over. As always, I am a side dish, this article is also a summary of the side of the side of the cake.

First, there are several issues at the conceptual level:

    • What kinds of memory structures are run in Java?
    • Why do you design stack separation in Java?
    • How is data sharing implemented in Java Multi-threading?
    • What is the basis of Java reflection?

Then the application level:

    • What is the difference between a reference type variable and an object?
    • What is the case with a local variable, and under what circumstances is a member variable?
    • How do arrays initialize? How do I allocate memory during the process of declaring an array?
    • Declares an array of primitive types and declarations of reference types, and when initialized, what are the extents of the memory allocation mechanism?
    • Under what circumstances is our approach designed to be static, and why? (The last time Mr. Hu asked Vincci, asked the speechless, then want to answer, but the old feeling expression is not clear, here also briefly explained)

OK, the problem is over, if you can see the answer, then, there is no need to waste your precious time to watch.

If you do not understand, please follow me all the way down.

Run-time memory structure in Java

1.1 Method Area:

A method area is a memory logical area allocated by the system that is used by the JVM to store type information (the description of the class) when it loads the class file.

The information stored in the method area includes:

Basic information about the 1.1.1 class:

    1. Fully qualified name of each class
    2. Fully qualified name of the direct superclass for each class (constrained type conversions)
    3. Whether the class is a class or an interface
    4. Access modifiers of this type
    5. Ordered list of fully qualified names for direct hyper-interfaces

1.1.2 More information about the loaded class:

    1. To run a constant-rate pool:

      In the method area, each type corresponds to a constant pool that holds all the constants used for that type, and the constant pool stores such as literal strings, final variable values, class names, and method name constants. They are accessed in an array form through an index, which is a bridge between external calls and classes and types of objects. (It may be a normal string, then parsed by a constant pool, it becomes a reference to a class)

    2. Field information:

      Field information holds information about each field declared in a class, including the name, type, and modifier of the field.

      A field name refers to an instance variable or class variable of a class or interface, and a field descriptor is a string that indicates the type of field, such as private a a=null; A is a field name, A is a descriptor and private is a modifier

    3. Method information:

      The information for each method declared in the class, including the method name, the return value type, the parameter type, the modifier, the exception, and the method's bytecode.

      (at compile time, the method's local variables, operand stack size and so on are determined and stored in the bytecode, when loaded, along with the class loaded into the method area.) )

      At run time, the JVM obtains a symbolic reference from a constant pool, then resolves the actual address of the referenced item at run time, and finally links the code in the current class or interface with the code in the other class or interface through the fully qualified name, method, and field descriptor in the constant pool.
    4. Static variables:

      This is nothing to say, is the class variable, all instances of the class are shared, we just need to know that there is a static zone in the method area, static zone dedicated to static variables and static blocks.

    5. A reference to the class ClassLoader: a reference to the class loader for the class.
    6. References to class classes: The virtual machine creates a class instance for each loaded type to represent the loaded class.

Thus we can know the basis of reflection:

When the class is loaded, all the information in the method area is added, and then an instance of class is formed, representing the loaded class. All the information in the method area can be reflected by this class object. We know that an object is an instance of a class, and a class is an abstraction of an object of the same structure. Each object in the same class has the same structure (attributes) and has the same function (method), and the individual objects differ only in the value of the property.
Similarly, all of our classes are actually instances of class, and they all have the same structure-----field array, method array. The properties in each class are a specific property value of the field property, and the method is a specific property value for the methods property.

At run time, the JVM obtains a symbolic reference from a constant pool, then resolves the actual address of the referenced item at run time, and finally links the code in the current class or interface with the code in the other class or interface through the fully qualified name, method, and field descriptor in the constant pool.

1.2 Java Stack

The JVM stack is a program runtime unit that determines how the program executes, or how the data is handled.

In Java, a thread will have a thread's JVM stack corresponding to it, because the thread execution logic is obviously different, so a separate JVM stack is required to hold the thread's execution logic.

Invocation of the method:

Java stack memory, as a frame of the local method of the call state, including the method call parameters, local variables, intermediate results, etc. (methods are stored in the form of method frames in the method area), each call to a method will be the method of the method frame into the Java stack, as the current method frame. When the call finishes (returns), the frame pops up.

This means that:

Some of the basic types of variables and reference variables that are 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 a memory space for the variable in the stack, and when the scope of the variable is exceeded (after the execution of the method is completed), Java automatically frees the memory space allocated for that variable, which can be used immediately by another. --------also, because the variable is freed, the object that corresponds to the variable loses its reference and becomes garbage that can be recycled by the GC object.

So we can know the difference between the member variable and the local variable:

Local variables, declared inside the method, when the method runs out, memory is freed.
Member variable, as long as the object is still there, even if a method has run out.
From a system perspective, declaring local variables facilitates more efficient use of memory space (the method runs out of recycle).
Member variables can be used to share data across methods.

The composition of the Java stack memory:
The local variable area, the operand stack, the frame data area compose.
(1): The local variable area is an array in words, and each array element corresponds to the value of a local variable. When a method is called, the local variables of the method are made into an array, accessed through an index. In the case of a non-static method, add an implied reference to the This parameter, which points to the object that called the method. The static method does not have this parameter. Therefore, the object cannot invoke a static method.

Thus, we can know when the method is designed to be static, when is non-static?

As mentioned earlier, an object is an instance of a class, with the same structure for each object, but with different properties.
A static method is an object that cannot be called.
Therefore, static methods are suitable for tool methods in the tool class, which are used only to implement some functions, and do not need to produce objects, by setting the properties of the object to get different individuals.


(2): The operand stack is also an array, but is accessed through a stack operation. The so-called operands are those that are instructed to manipulate the data. When a parameter operation is required, such as A=B+C, the parameters to be manipulated will be stacked, such as the B and C stacks, which are then ejected by the action instruction, and the operation is performed. The virtual machine takes the operand stack as the workspace.


(3): Frame data area processing constant pool resolution, exception handling, etc.

1.3 Java Heap

The Java heap is a run-time data area that stores the cells of the data, and stores the new objects and arrays created by the New keyword, from which the object allocates memory.
Objects declared in the heap are not directly accessible and must be called by a variable that is declared in the stack to the reference. A reference variable is a name that is an array or an object, and you can use reference variables from the stack to access the arrays or objects in the heap later in your program.

From this we can see the difference between a reference type variable and an object:

Declared objects are initialized in heap memory and are really used to store data. cannot be accessed directly.

Reference-type variables are stored in the stack, a symbol that refers to objects in the heap (pointers).

Heap vs. Stack comparison:
The Java heap and stack are all used to store data, so what is the difference between them? Since stacks can also store data, why design heaps?

1. From the point of view of storing data:

We have explained earlier:

A variable of the underlying type or reference type that is stored in the stack

The object or array object is stored in the heap.

In the stack, the reference variable has a size of 32 bits and a base type of 1-8 bytes.
However, the size of the object and the size of the array is dynamic, which also determines the dynamic nature of the data in the heap, because it is dynamically allocated memory at run time, the lifetime does not have to be determined at compile time, Java garbage collector will automatically take away the data that is no longer used.

2. From the perspective of data sharing:

1). In a single thread class, the data in the stack can be shared

For example we define:

Java code
    1. int a=3;
    2. int b=3;

The compiler processes int a = 3 First, it creates a reference to a variable in the stack, and then finds out if there is a value of 3 in the stack, and if it does not, it stores the 3 in and then points a to 3. then the int b = 3 is processed, and after the reference variable of B is created, because there are already 3 values in the stack, B points directly to 3. In this case, A and B both point to 3.

And if we define:

Java code
    1. Integer a=new integer (128);//(1)
    2. Integer b=new integer (128);//(2)

At this point the execution process is: at Execution (1), a variable A is first created in the stack, then an object is instantiated in the heap memory, and the variable A is pointed to the instantiated object. At Execution (2), the procedure is similar, at which time, in heap memory, there will be two integer types of objects.

2). The sharing of data between the threads of the process is implemented through the heap

So, how is our data sharing implemented in multithreaded development?

The data in the heap is shared by all line stacks, and we can pass the data from one heap to the working memory of each stack through parameter passing, thus realizing data sharing among multiple threads.

(data sharing across multiple processes needs to be transmitted over the network.) )

3. From the perspective of the program design:

From the point of view of software design, the JVM stack represents the processing logic, and the JVM heap represents the data. This separation makes the processing logic clearer. The idea of divide and conquer. This idea of isolation and modularity is reflected in every aspect of software design.

4. Value passing and reference passing the truth

With this understanding of stacks and heaps, it's easy to know the truth about value passing and referencing:

1. The program runs always in the JVM stack, so when parameters are passed, there is only a problem passing the base type and object references. The object itself is not passed directly.

But how is the illusion of citation caused?

In running the JVM stack, the basic type and the reference are treated the same, all of which are pass values, so if it is a reference to a method call, it can also be understood as a "pass-through value" invocation, that is, the reference processing is exactly the same as the base type.

However, when the called method is entered, the value of the reference being passed is interpreted (or found) by the program to the object in the JVM heap, which corresponds to the actual object.

If you modify at this point, you modify the reference object instead of the reference itself, which is: the data in the JVM heap is modified. So this is a change that can be maintained.

At last:

In a sense, objects are made up of basic types.

You can look at an object as a tree, the object's properties, if it is an object, is still a tree (that is, a non-leaf node), and the base type is the leaf node of the tree. When a program parameter is passed, the passed value itself cannot be modified, but if the value is a non-leaf node (that is, an object reference), you can modify all the content underneath the node.

In fact, the object-oriented approach to the implementation of the previous structured program is not any different.

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

When we take the object apart, the object's properties are data, stored in the JVM heap, and the object's behavior (method) is run logic, placed in the JVM stack. When we write the object, we write the data structure, and also write the logic of the processing.

Java runtime, various types of storage introduction

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.