Java memory management: deep into the Java memory area

Source: Internet
Author: User
Java memory management: deep into the Java memory area

This article references: a deep understanding of Chapter 2nd of Java Virtual Machine

There is a wall between Java and C ++ that is surrounded by the dynamic memory allocation and garbage collection technology. The people who look at it want to go in, but the people inside the wall want to come up with it.

Overview:

For developers engaged in C and C ++ program development, in the memory management field, they are not only the emperor with the highest power, but also the working people who are engaged in the most basic work-have every

The "ownership" of an object is responsible for the maintenance from the beginning to the end of every object's life.

With the help of the Automatic Memory Management Mechanism of virtual machines, Java programmers no longer need to write paired delete/free code for each new operation, and it is not easy to see

Memory leakage and memory overflow appear to be good for managing memory by virtual machines. However, it is precisely because the Java programmer has handed over the memory control power to the Java Virtual Machine.

Memory leakage and overflow may occur. If you do not know how the VM uses the memory, troubleshooting will become an extremely difficult task.

 

Data Area During Running

When executing a Java program, the Java Virtual Machine divides the memory it manages into several different data regions. These regions have their own purposes and are created and destroyed

Some regions exist with the startup of virtual machine processes, and some regions are established and destroyed by the startup and termination of user threads. According to Java virtual machine specification (version 2nd)

The memory managed by the Java Virtual Machine will include the following runtime data areas, as shown in:

          

Program counters

The Program Counter Register (Program Counter) is a small memory space. Its function can be seen as the row number indicator of the bytecode executed by the current thread. In the virtual

In the conceptual model of the machine (only the conceptual model, various virtual machines may be implemented in a more efficient way), the bytecode interpreter selects the counter value when working.

The next bytecode command to be executed depends on this counter for basic functions such as branch, loop, jump, exception handling, and thread recovery.Because the Java Virtual Machine is multiline

ChengIt is implemented by switching threads in turn and allocating the execution time of the processor. At any definite moment, a processor (for a multi-core processor, it is an internal

Core) Only executes the commands in one thread. Therefore, in order to restore the thread to the correct execution position after switching, each thread requires an independent program counter, each

Counters between threads do not affect each other. They are stored independently. We call this type of memory region as "thread-private" memory.If the thread is executing a Java method, this counter

The address of the VM bytecode command being executed is recorded. If the Natvie method is being executed, the counter value is null (Undefined ).This memory region is the only one

InThe Java virtual machine specification does not specify any OutOfMemoryError conditions.

 

Java Virtual Machine Stack

Like program counters, Java Virtual Machine stack (Java Virtual Machine Stacks) is also proprietary to threads, and its lifecycle is the same as that of threads. The Virtual Machine stack describes Java

Memory Model for method execution: A Stack Frame is created simultaneously when each method is executed)Used to store local variable tables, Operation stacks, dynamic links, and method exits

And so onInformation.The process of calling each method until execution is complete corresponds to the process of a stack frame in the VM Stack from the inbound stack to the outbound stack.

Java memory is often divided into Heap memory and Stack memory. This method is rough, and the Division of Java memory areas is actually far more complex than this. This Division

The popularity of this method only shows that the most important memory area for most programmers and the most closely related to object memory allocation are the two. The "heap" mentioned here will be detailed later

"Stack" is the virtual machine stack, or the local variable table section in the Virtual Machine stack.

The local variable table stores various basic data types (boolean, byte, char, short, int, float, long, and double) that are known during the compilation period, and object references.

(Reference type), which is not the same as the object itself. According to the implementation of different virtual machines, it may be a reference pointer pointing to the starting address of the object, or it may point to

Handle or other locations related to the object) and returnAddress type (pointing to the address of a bytecode instruction ).

Data of the 64-bit long and double types occupy two local variable spaces.(Slot), the remaining data types only occupy 1.Memory required for the local variable table

Space allocation completed during compilationWhen you enter a method, the size of the local variable space allocated in the frame is completely determined and will not be changed during the method running.

Local ChangeThe size of the table.In the Java Virtual Machine specification, two exception conditions are specified for this region: If the stack depth requested by the thread is greater than the depth allowed by the virtual machine

StackOverflowError is abnormal. If the VM stack can be dynamically expanded (currently, most Java virtual machines can be dynamically extended, but the Java Virtual Machine specification also allows a fixed length

Virtual Machine stack). When the extended memory cannot be applied for, an OutOfMemoryError exception is thrown.

 

Local method Stack

THE Native Method Stacks plays a very similar role with the Virtual Machine stack. The difference is that the virtual machine stack executes the Java Method (that is, the word

Code), while the local method stack is the Native method service used by virtual machines. The language, usage, and data structure of the method in the local method stack in the virtual machine specification are not

There are mandatory rules, so the specific virtual machine can freely implement it. Even some virtual machines (such as Sun HotSpot virtual machines) directly combine the local method stack with the Virtual Machine stack. And

Like a virtual machine stack, StackOverflowError and OutOfMemoryError are thrown in the local method stack area.

 

Java heap

For most applications, Java Heap is the largest memory managed by Java virtual machines. Java heap is a memory area shared by all threads. It is created when the VM is started.In

The only purpose of the storage region is to store object instances., Almost all object instances are allocated memory here. This is described in the Java Virtual Machine specification: All object instances and arrays must be allocated on the stack,

However, with the development of JIT compiler and the gradual maturity of escape analysis technology, stack allocation and scalar replacement optimization will lead to some subtle changes, all objects are allocated to the stack and gradually become more and more "absolute ".

Yes.

Java Heap is the main area of the Garbage collector management, so it is often called "GC Heap" (Garbage Collected Heap, but it was not translated into "Garbage" in China "). From the perspective of memory recovery,

Currently, the collectors are basically used.Generational collection AlgorithmTherefore, the Java heap can be subdivided into the new generation and the old generation, and the Eden space, From the original vor space, To the original vor space.

. IfFrom the perspective of memory allocation, the Java heap shared by threads may divide private allocation buffers for multiple threads.(Thread Local Allocation Buffer, TLAB ). However

Points are irrelevant to the storage content. No matter which region, the storage is still an object instance. The purpose of further division is to better recycle the memory or allocate the memory faster. In this chapter, we only apply to the memory Zone

The role of the domain is discussed. The details of the distribution and collection of the above regions in the Java heap will be the topic of the next chapter.

According to Java Virtual Machine specifications, Java heap can be in physically discontinuous memory space, as long as the logic is continuous, just like our disk space. In implementation, it can be fixed

But the current mainstream virtual machines are implemented according to the Scalability (through-Xmx and-Xms control ). If the heap does not have memory for instance allocation, and the heap cannot be extended

Will throw an OutOfMemoryError.

 

Method Area

The Method Area, like the Java heap, is the memory Area shared by each thread.Stores information about classes loaded by virtual machines, constants, static variables, and Code Compiled by the real-time compiler.

Data. Although the Java Virtual Machine specification describes the method area as a logical part of the Heap, it has an alias called Non-Heap (Non-Heap), which should be distinguished from the Java Heap.

For developers who are used to developing and deploying programs on the HotSpot virtual machine, many people are willing to call the Method Area "Permanent Generation". In essence, the two are not equivalent, only because

The design team for the HotSpot Virtual Machine chooses to extend GC generation collection to the method area, or use permanent generation to implement the method area. Other virtual machines (such as BEA JRockit and IBM J9) do not exist.

Permanent generation concept. Even the HotSpot virtual machine itself, according to the official release of the road map information, has now abandoned permanent generation and "move" to Native Memory to implement the planning of the method area.

The Java virtual machine specification imposes very loose restrictions on this region. In addition to the same Java heap, it does not require continuous memory and can be fixed or scalable. In addition, it can also choose not to implement garbage collection. Relatively speaking,

Garbage collection rarely occurs in this area, but it is not because the data enters the method area and is "permanent" like the permanent name. The memory recovery target in this region is mainly for the collection of constant pools and types of pairs.

In general, the "score" of the recovery in this region is difficult to meet, especially the type of unloading, the conditions are quite harsh, but the recovery in this part of the region is indeed necessary. In Sun's BUG list,

Several serious bugs that have occurred are caused by memory leakage because the HotSpot virtual machines of earlier versions are not fully recycled in this region. According to the Java Virtual Machine specification, when the method area cannot meet the memory allocation

When required, an OutOfMemoryError is thrown.

 

Runtime constant pool

  The Runtime Constant Pool is part of the method area.. In addition to descriptions such as the version, field, method, and interface of the Class, the Class file also contains a constant pool.

(Constant Pool Table ),Used to store various literal and symbolic references generated during compilation., This part of content will be stored in the runtime pool of the method area after the class is loaded.Java Virtual Machine

The format of each part of a file (including the constant pool) is strictly specified, and each byte is used to store which data must comply with the standard requirements, this will be recognized, loaded, and executed by the virtual machine. But

Runtime frequent volume pool. Java Virtual Machine specifications do not require any details. virtual machines implemented by different providers can implement this memory area as needed. However, in general, apart from saving the Class

In addition to the symbolic references described in the file, the translated direct references are also stored in the runtime pool. Another important feature of the runtime constant pool over the Class file constant pool is its dynamic nature.

Constants are not required to be generated only during the compilation period, that is, they are not the content of the constant pool preset into the Class file before they can enter the method zone runtime constant pool, during running, new constants may also be placed in the pool.

The intern () method of the String class is used by developers. Since the runtime constant pool is part of the method area, it is naturally limited by the method Area Memory. When the constant Pool cannot be applied to the memory, it will throw

OutOfMemoryError is abnormal.

 

Object Access

After introducing the runtime data zone of the Java Virtual Machine, we can discuss a question: how does object access work in Java? Object Access is ubiquitous in Java and is the most common process.

Sequential behavior, but even the simplest access involves the association between the three most important memory areas of Java stack, Java heap, and method zone. The following code is as follows:

          Object obj = new Object ();

Assuming that the code appears in the method body, the semantics of the "Object obj" part will be reflected in the local variable table on the Java stack, and will appear as a reference type data. And the "new Object ()" part

Is reflected in the Java heap, forming a structured memory that stores all Instance Data values of the Object type (Instance Data, Data of various Instance fields in the Object, based on the specific type and Virtual Machine implementation

Object Memory Layout (Object Memory Layout), the length of this Memory is not fixed. In addition, the data of this object type (such as object type, parent class, and real

The current interface, method, and so on. These types of data are stored in the method area.

  Because the reference type only specifies a reference pointing to an object in the Java Virtual Machine specification, it does not define the method in which the reference should be located and accessed to

Image LocationTherefore, different virtual machines implement different object access methods. There are two mainstream access Methods: Using handles and direct pointers. If you use the handle access method, the Java heap will

Divide a piece of memoryHandle pool, which stores the handle address of the object. The handle contains the specific address information of the object instance data and type data., As shown in:

 

      

  If direct pointer access is used, you must consider how to place information related to access type data in the layout of Java heap objects,The object address is directly stored in reference., As shown below

FigureDescription:

      

  The two object access methods have their own advantages. The biggest advantage of using the handle access method is that the reference stores a stable handle address and the object is moved (when the object is moved during garbage collection, the object is not

Usually common behavior), only the instance data pointer in the handle is changed, and the reference itself does not need to be modified. The biggest advantage of direct pointer access is faster speed, which saves a pointer

The time overhead of positioning. Because objects are frequently accessed in Java, this overhead is also a considerable execution cost.Sun HotSpot, the main virtual machine discussed in this book

It uses the second method for object access, but from the perspective of software development, it is also common for various languages and frameworks to use handles for access.

 

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.