Java Virtual machine garbage collector and memory allocation policy

Source: Internet
Author: User

Java Virtual machine garbage collector and memory allocation policy overview
  • Those memory needs to be recycled and when to recycle. How to recycle is 3 things the GC needs to complete.
  • Program counter. The three regions of the virtual machine stack and the local method stack are thread-private, memory allocation and recycling are deterministic, and memory is recycled as the method ends or the thread ends.

  • The Java heap and the method area are not known to create those objects until the execution time, and this part of the memory allocation is dynamic. The memory allocated and reclaimed in this chapter note refers to the Java heap and method area .

Infer that the object is dead.
  • Reference counting algorithm: Add a reference counter to the object whenever there is a place to reference it, counter +1; Reference fails, counter-1. The counter is 0 to infer that the object is dead.

    In this way, however, it is very difficult to solve the problem of circular references between Java objects. So the mainstream Java virtual machine does not use this method to infer whether an object survives.

  • Reachability Analysis: A GC roots as a starting point for these nodes to search down through the reference chain (Reference Chain), when a GC roots no reference chain can reach an object A, a can feel that the object is not available. Such objects can be judged as recyclable objects
1. References
  • Narrow definition of a reference: when the value stored in the reference type data is the starting address of a block of memory, it is said that this memory represents a reference.

    But such a way can not describe some of the "food tasteless, discard" object

  • After JKD1.2, the reference concept is expanded, and the object is divided into strong references (strong regerence), soft references (Soft Reference). Weak references (Weak Reference), virtual references (Phantom Reference)
  • (1) A strong citation refers to a reference to the new type, which is just a good quote. The collector never reclaims the referenced object
  • (2) Soft references are used to describe some practical, but not necessary, objects. When the system is going to have a memory overflow, this kind of object will be recycled two times, assuming that the space is not enough. Throw Oom
  • (3) Weakly referenced objects can only survive until the next collection occurs. Whether or not memory is sufficient.

  • (4) A virtual reference is the weakest reference relationship, and setting a virtual reference for an object is only intended to receive a system notification when the object is recycled.

2. Recovery method Area
  • The Java Virtual Machine specification said it would not require the reclamation method area (permanent generation). In the Cenozoic. Garbage collection can reclaim more than 70% of memory at a time. However, the collection efficiency in the method area (permanent generation) is often low. The main collection is obsolete constants and useless classes.

  • Obsolete constants refer to the existence of a string ABC for a constant pool. But the current system has no object to reference ABC, then ABC is a constant that can be discarded and can be recycled
  • Useless class: (1) The object of this class has been completely recycled. (2) The ClassLoader loaded into the class have been recycled. (3) The corresponding class object is not referenced anywhere. And through the reflection interview. The hotspot provides a-XNOCLASSGC parameter to control whether or not to recycle useless classes
Garbage collection algorithm
  • Classic frequently used collection algorithms: Tag-purge algorithm (mark-sweep), tagging-collation (mark-compact), Replication algorithm (Copying), "generational collection" of mainstream virtual machines
1. Tag-Clear algorithm
  • Tag cleanup is the most basic collection algorithm: 1. Mark the objects that need to be recycled. 2. After the mark is complete, all the tagged objects are collected uniformly.
  • The mark clear algorithm is insufficient: 1. Not high efficiency.

    2. After removal, a large number of discontinuous fragments are generated. Assuming that these discontinuities are not enough space to store the resulting object, it also triggers another collection action ahead of time. Reduce memory efficiency.

2. Replication algorithm:
  • The replication algorithm divides the memory into two equal blocks, a and a, each time using a piece of memory such as a, when a memory is full, the remaining surviving objects are copied to B memory, a one-off cleanup. Strengths: Achieve simple execution efficiency. And you don't have to think about the memory fragments that are similar to the markup cleanup method.

    The disadvantage is that the original memory is only used in half, the cost is too high.

  • Most of the current mainstream commercial virtual machines use this way to collect the new generation. The new generation of object 98% is to die in the face of life. Therefore, it is not necessary to allocate Cenozoic memory according to 1:1. The distribution as Hotspot is: 8 (Eden): 1 (from Survivor): 1 (to survivor). At the same time use the old age for memory allocation guarantees.
3. Labeling-Finishing (mark-compact)
  • The replication collection algorithm is used when the object has a high survival rate. Will generate a lot of replication work. Affect performance.

    Because of the old age. General objects are relatively large, and the survival rate is high, it is generally not possible to use the algorithm.

  • The marker-collation algorithm is based on the high survival rate of the old age object and the larger object. The rationale is consistent with the markup cleanup, but the next step is not to purge directly, but to move all surviving objects to one end and then clear out the memory outside the end boundary.
4. Generation of collection algorithms
  • The virtual machine memory is mainly divided into the new generation and the old age, the new generation generally uses the replication algorithm, from the old age distribution guarantee. The old age was recycled using the tag grooming algorithm.
Hotspot Main algorithm realizes
  • The Gc-root node is looking for a reference chain, and the Gc-root node is generally constant. Static variables, local variable table data. When applying a lot of methods, look for a reference chain for this operation. Will consume very much time
  • The accessibility analysis, the time sensitive also body now GC pauses, analysis of the time. It is required that the system is stopped, and the object reference relationship is constantly changing while the accessibility analysis is not possible. That is, "Stop the word".
  • The exact GC used by the current mainstream virtual machines: in the hotspot implementation, a set of data structures called Oopmap are used to achieve this purpose. When class loading is complete. During the JIT (even compiler) compilation process. The positions in the stack are referenced in a particular location.

    This allows the GC to know this information directly when it is scanned.

  • Safety point: With the help of Oopmap, the hotspot can complete the Gc-root enumeration at high speed and accuracy, but Oopmap's content change instruction is very many. Assume that the corresponding oopmap are generated for each instruction. Need to consume a lot of extra space. So. Only the ability to record these oopmap information in a specific location (Security point: SafePoint) . Method calls, loop jumps, exception jumps, and so on are the instructions for these functions to produce safepoint.
  • Safe zone: A security zone is a piece of code that refers to a relationship that does not change, and when the thread executes to the security zone, it first marks itself into the security zone, and this time the JVM executes the GC without having to take care of the threads of those states, and when the thread is out of the security zone, The first check is whether the system has completed the GC root election, assuming that the execution continues, assuming that it is not finished waiting until a signal can be safely left.

Hotspot Basic garbage collector

The generational algorithm can divide the collector into the new generation collector and the old age collector.

1. The new generation collector mainly includes: Serial (serial), parnew (parallel), Parallel scavenge (parallel); 2. Old age collectors mainly include: Serial old,parallel old,cms (Concurrent Mark Sweep).

  • Serial is the oldest, single-threaded, new generation collector that, when collecting actions, must suspend all other worker threads until the collection is over.

    The collector is almost the fastest and most efficient collector in a single CPU. Serial is still a very good choice for virtual machines in client mode, and recovering from the new generation of one hundred or two hundred trillion is basically within 100 milliseconds, and these pauses are fully acceptable

  • Parnew is the multithreaded version number of serial, which is the preferred collector for virtual machines in service mode, mainly because it can be used in conjunction with the mainstream old age collector cms.

    The number of threads used by the collector is the same as the CPU core.

  • The Parallel scavenge collector is the focus is the throughput (throughput = Execute user code time/(Execute code time + garbage Collection Time)), the shorter the pause time. The better the user experience. High throughput makes it possible to use CPU time efficiently. Finish the task as soon as possible. This collector is suitable for a large number of background operations without the need for too many interactive systems. This collector is also called the throughput priority Collector.
  • Serial old uses a tagging algorithm . Like the serial collector, it is a single-threaded collector.

    Typically used in client execution mode.

  • Parallel old is a Parallel scavenge collector used in conjunction with a tag collation algorithm , assuming that the Cenozoic uses the Paraller scavenge algorithm. In the old age, you can only use the parallel and the serial older algorithms. In the focus on the throughput system. Priority is given to paraller scavenge and parallel old algorithms.
CMS collector

It is the mainstream collector of the current old age, which adopts the mark clearing algorithm. The whole process of CMS is divided into 4 steps: 1. Initial tag. 2. Concurrent tagging; 3. Mark again; 4. Concurrent cleanup. In the initial tag, another token still needs to stop the world.

  • The initial tag is simply a record of the objects that GC root can directly relate to, very fast, and the concurrent tagging phase is the GC Roots tracing. Another tagging phase is to fix the tag record of the part of the object that the user continues to manipulate during the concurrent tag.
  • Time-consuming concurrent tagging and concurrent cleanup steps that work with the user thread without the need to stop the world. The advantages of CMS are now collected concurrently, with low pauses.
  • CMS Disadvantage 1: Very sensitive to CPU resources. It is not recommended to use this collector at less than 4 cores. The number of recycle threads initiated by the CMS by default is (number of CPUs +3)/4.
  • CMS disadvantage 2:cms There is no way to handle floating garbage. Because after the tag. The user thread is still executing and will produce other garbage that remains in the next collection.

    After jdk1.6, the CMS collector boot threshold has been increased to 92%, assuming that the remaining 8% of the old age can not meet the floating garbage distribution, the concurrent Mode Failure will appear. This results in full GC generation.

    It is also possible to temporarily enable serial old to collect again for the older generation, but this will take a long time to pause. The-xx:cmsinitiatingoccupancyfraction property sets the startup threshold for the CMS and can reduce the startup threshold based on the actual appropriate value.

  • CMS Disadvantage 3: Using the tag cleanup algorithm. Can generate a lot of space for fragmentation. Assume that you cannot find a large enough contiguous space to allocate the current object. The full GC is triggered once.
G1 Collector

The G1 collector is considered a critical evolutionary feature of the Hotspot jdk1.7 and is a service-oriented garbage collector. G1 has the following advantages

  • Parallel and Concurrency: G1 can more fully apply the hardware advantages of multi-CPU, multi-core environment, and reduce the system downtime. G1 can allow Java programs to continue executing in a parallel way.
  • Generational collection: G1 does not need to be combined with other collectors to manage the entire GC heap independently. It can handle new objects in different ways and old objects that have survived multiple GC to produce better collection results.
  • Spatial integration: G1 is a collector based on the tag grooming algorithm, which does not generate large amounts of discontinuous fragmentation space, which is much better than the CMS.
  • Pre-measured pauses: Reduced pauses are almost all of the current Internet enterprise application concerns. G1 In addition to the pursuit of low pauses, but also established a predictable pause time model, allowing the use of this designation in a millisecond time fragment of length m, the collection consumes no longer than n milliseconds. Some of the real-time garbage collectors have been featured.
  • Other collectors are collected throughout the new generation and throughout the old age, G1 the entire heap into separate regions of equal size (region), and the new generation and the old age are not required to be associated with the area. At the time of recycling, there is a priority list that prioritizes the recovery of the region with the highest value, ensuring that the G1 collector gets the highest possible collection efficiency for a limited period of time.
  • Region: Each region has a corresponding remembered Set.

    Each time the operation is reference, it is assumed that the referenced object is checked in another region. The remembered Set is logged. Use remembered set as a gc-root. Can guarantee that the whole heap does not scan, and there will be no recycling omissions.

  • The G1 collector assumes that maintenance remembered set operations are not calculated. Can be divided into the following steps: 1. Initial tag. 2. Concurrent tagging; 3. Finally marked. 4. Filter collection
Memory allocation policy
  • Object Precedence in Eden Assignment
  • Large objects go straight into the old age: the large objects in the code to avoid short-lived. -xx:pretenuresizethreshold=3145728 indicates that objects larger than 3M are allocated directly in the old age.
  • Long-term survival into the old age: virtual machines Each object is an age counter, and the object survives every time the minor GC goes through. Age+1. Reach a certain age value (default 15), enter the old age.

    -xx:maxtenuringthreshold=1 says that every time a GC is minor, the surviving object will enter the old age.

  • Dynamically infer object age: Assuming that the sum of the same age object in Survivor is greater than half the size of survivor space, objects older than or equal to that age go directly into the old era.
  • Space Allocation Guarantee: Creating objects New generation assuming that there is not enough space, the old age allocates memory, which requires that the old age has a continuous space to hold the object, otherwise the guarantee will fail. Triggering full GC
Summary

This content mainly introduces several garbage collection algorithms, several major virtual machine collectors and the main strategy of memory allocation. Choose whether to focus on the pause or the throughput, serial or parallel collector, depending on the detailed scenario. is an important part of tuning. Understand memory allocations at the same time. There is also a certain improvement in writing Java code.

Java Virtual machine garbage collector and memory allocation policy

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.