JVM Virtual machine memory model in Java detailed description

Source: Internet
Author: User

JVM Virtual machine memory model in Java detailed description

2012-12-12 18:36:03|   Category:  java  |   Tags: java   jvm   heap Memory    virtual machine   | report | font   subscription

The internal structure of the JVM is as follows:


An excellent Java programmer must understand the Java memory model, how GC works, and how to optimize GC performance, limited interaction with GC, some applications have high performance requirements, such as embedded systems, real-time systems, etc., only to comprehensively improve the management efficiency of memory To improve the performance of the entire application.

This article discusses the JVM memory model, the GC's working principle, and several key issues in GC to improve the performance of Java programs from a GC perspective.

1 Java memory is divided into:

Program Counter (the line number indicator of the byte code executed by the current thread, the bytecode interpreter chooses the next bytecode instruction by changing the value of the counter, branching, looping, exception handling, etc.). Each thread has a separate program counter, which belongs to the thread-private memory area),

Java Virtual machine stack (also is the line private, stores the local variable, the operation Stack, each method executes when creates a stack frame, the execution process is the stack the stack operation),

Local method Stack (execute native method),

Young Generation Heap (Eden, from Survivor, to survivor), Old generation heap (after several garbage collection, preserved),

The persistent generation heap (also called the method area, holds the constant pool and type data information, is not recycled),

Direct Memory (use the native method to directly allocate out-of-heap memory, and then operate through the directbytebuffer in the heap as a reference to this memory)

2 There are two types of object access: Through the handle pool and directly through the pointer, the benefit of the handle pool is that after garbage collection, you do not need to change the object reference, as long as the handle reference is changed, the advantage of the direct pointer is high efficiency.

Refer to "Deep Java Virtual Machine Chapter II"

Explains the significance of the minor GC and major GC, and the two survivor zone to the replication collection algorithm

3 JVM Memory mechanism

Four types of reference parsing in Java memory, strong references, weak references, soft references, virtual references

4 Garbage collection algorithm

4.1 Reference count, high efficiency, but unable to solve the problem of useless object circular reference. A timely reference count is greater than 0, but is not available.

4.2 Objects up to the way Java virtual machines are used. Can be used as the root object: objects referenced in the virtual machine stack frame, objects referenced in the method area (persistence) class static property (class static properties have allocated space for this property before the instance was created, a good instance was created, shared in all instances of the class), objects referenced by constants in the method area (such as constant strings), The object referenced in the local method stack (the native method).

4.3 Reference strength, strong (that is, the traditional understanding of the reference, Obj=new obj ()), soft (softreference, before the memory overflows, the GC will take this part into the recycling range, two times, if there is not enough memory, then Oom), Weak (WeakReference, once the GC is recycled, regardless of whether the memory is sufficient will be recycled), virtual (have a virtual reference does not affect the life cycle, unable to obtain an object through a virtual reference, the only effect is that the object is recycled can get a system notification, phantomreference)

4.4 Objects are called only once in a finalize () before being recycled, and can save themselves in finalize and refer to themselves. Only if the object overrides the Finalize () method is placed in the queue that performs finalize (). This is not recommended and can be replaced with try{} finally.

4.5 Java Recovery algorithm

Tag cleanup, inefficient, generates memory fragmentation.

Copy collection algorithms, more mainstream algorithms, partitioning, eden,survivor, moving objects that have not been reclaimed to the survivor area, and then clearing the Eden area once. This algorithm is suitable for the case that the object survival rate is not high, and some allocation space should be sacrificed, generally eden:survivor=8:1.

When the object survival rate is very high, the efficiency of the replication collection algorithm will be problematic, so there is a tag-collation algorithm. Organize all the surviving objects to one end, and then clean the other end directly.

The generational algorithm, Java memory is generally divided into the Cenozoic and old generation, according to the characteristics of the survival rate of two regional objects, respectively, using the copy-collect algorithm and marker-cleanup (marker-collation) algorithm.

4.6 Garbage collector

Serial collector, single thread collection. Very hateful, will stop other user threads. A bad user experience. However, it is suitable for client side, because the amount of garbage produced is small, the recovery is fast, and dozens of milliseconds is solved.

Parnew Collector, as with serial. The difference is that the multithreading mechanism is used when collecting.

The CMS collector, which allows the collection thread and the user thread to execute concurrently, is unfortunately used as a collector for older generations only with the above two unreliable collectors. It is an old generation collector that targets the shortest pause time, using the Mark-sweep algorithm (Mark-erase). The recycle step is the initial tag (stop world), the concurrency token, the re-tagging (stop world), and the concurrent cleanup. Stop World is a short time, so it can be thought of as a collector of user threads concurrency.

The parallel scavenge collector, which is a concurrent collector, can coexist with the user thread. Throughput can be controlled by parameters = user thread time/(user Time + garbage collection Time), foreground program is suitable for low throughput, reduce the time of user operation every time, and background program is suitable for high throughput, and the background calculation is completed as soon as possible. Also known as the throughput priority collector. The collector can also set the adaptive mode, which dynamically adjusts the throughput according to the actual situation.

The serial old collector, like serial, is used for collection in older generations. Use the tag grooming algorithm.

The parallel old collector, used in conjunction with parallel scavenge, is the best partner for parallel scavenge.

G1 (garbage first) collector, the most cutting-edge, jdk1.6 enters the trial period. Using the tag-collation algorithm, and the new zone, the partition has different priority, the priority is to collect the memory more full area. With high concurrency and low pauses, it is also a collector of agility.

5 Basic Experience

Minor GC is run in the Cenozoic Gc,major GC is run in the old generation of GC, 10 times times slower than minor.

Large objects are most likely to go directly into the old generation, and the program avoids short-lived large objects (arrays, lists).

Once minor was not collected, from Eden into the survivor, each time Gc,survivor plus one year old, until the age of N entered the old quarter.

Based on how the GC works, we can make the GC run more efficiently and meet the requirements of the application in a number of tricks and ways. Some suggestions on programming:

1) The most basic suggestion is to release the reference of the useless object as soon as possible. Most programmers use temporary variables to have the reference variable automatically set to null after exiting the active domain (scope). When we use this approach, we must pay special attention to complex object graphs, such as arrays, queues, trees, graphs, etc., which are more complex to refer to each other. For such objects, GC recycling is generally less efficient. If the program allows, the unused reference object will be assigned null as soon as possible, which can speed up the work of the GC.

2) Use the Finalize function as little as possible. The Finalize function is a chance that Java provides programmers with an opportunity to release objects or resources. However, it will increase the amount of GC work, and therefore minimize the use of a Finalize method to reclaim resources.

3) If you need to use a frequently used picture, you can use the Soft app type. It can save the picture in memory as much as possible for the program to call, without causing outofmemory.

4) Note the collection data types, including arrays, trees, graphs, linked lists and other data structures, which are more complex for GC to recycle. Also, be aware of some global variables, as well as some static variables. These variables tend to cause hanging objects (dangling reference), causing memory waste.

5) When the program has a certain wait time, the programmer can manually execute System.GC () to notify the GC to run, but the Java language specification does not guarantee that the GC will be executed. Using incremental GC can shorten the pause time for Java programs.

JVM Virtual machine memory model in Java detailed description

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.