Jvm gc description

Source: Internet
Author: User

Post address: http://hi.baidu.com/mailluzhou/item/98052fdc701baade241f4008

1. Related Concepts

Basic recycling Algorithm

  1. Reference counting)
    The old recycling algorithm. The principle is that this object has a reference, that is, adding a count. deleting a reference reduces the count. During garbage collection, only objects with zero collection count are used. The most critical issue of this algorithm is that it cannot handle circular references.
  2. Mark-sweep)
    This algorithm is executed in two phases. In the first stage, all referenced objects are marked from the reference root node. In the second stage, the whole heap is traversed to clear unmarked objects. This algorithm suspends the entire application and generates memory fragments.
  3. Copy)
    This algorithm divides the memory space into two equal regions and uses only one of them at a time. During garbage collection, traverse the current region and copy the objects in use to another region. The secondary algorithm only processes objects in use at a time, so the replication cost is relatively small. At the same time, the corresponding memory can be organized after the replication, but there is a "Fragmentation" problem. Of course, the disadvantage of this algorithm is also obvious, that is, it requires two times of memory space.
  4. Mark-compact)
    This algorithm combines the advantages of "tag-clear" and "copy" algorithms. It is also divided into two phases. In the first phase, all referenced objects are marked from the root node. In the second stage, the whole heap is traversed to clear unlabeled objects and compress the surviving objects to one of the heap, discharge in sequence. This algorithm avoids the "tag-clear" fragmentation problem, and also avoids the space problem of the "copy" algorithm.
  5. Incremental collecting)
    The garbage collection algorithm is implemented, that is, garbage collection is performed simultaneously by the application. I don't know why the Collector in jdk5.0 does not use this algorithm.
  6. Generational collecting)
    Based on the garbage collection algorithm obtained after object lifecycle analysis. Objects are divided into young, old, and persistent generations. Different algorithms (one of the above methods) are used to reclaim objects in different lifecycles. The current garbage collector (beginning with j2se1.2) uses this algorithm.

Generation Garbage Collection details


Shows the Generation Distribution in the Java heap.

  1. Young (young generation)
    The young generation is divided into three zones. One Eden zone and two vor zones. Most objects are generated in the Eden area. When the Eden zone is full, the surviving objects will be copied to the primary vor zone (one of the two). When the primary vor zone is full, the surviving objects in this region will be copied to another region vor. When the region VOR is full, the surviving objects will be copied from the first region vor, it will be copied as "tenured )". Note that the two regions of the same vor are symmetric and irrelevant. Therefore, objects copied from Eden and copied from the previous vor may exist in the same region, only objects copied from the first vor region are copied to the old district. In addition, there is always a blank vor area.
  2. Tenured (elder generation)
    The old generation stores objects that survive from the young generation. Generally, the old generation stores objects with long life periods.
  3. Perm (permanent generation)
    Used to store static files. Currently, Java classes and methods are supported. Persistent generation has no significant impact on garbage collection, but some applications may dynamically generate or call some classes, such as hibernate, in this case, you need to set up a large persistent storage space to store the classes added during the running process. The persistent generation size is set by-XX: maxpermsize = <n>.

GC type
There are two types of GC:Scavenge GC and full GC.

  1. Scavenge GC
    Generally, when a new object is generated and the Eden application fails, scavenge GC is triggered, and GC is performed in the heap Eden area to clear non-surviving objects, and move the surviving objects to the same vor area. Then, sort out the two zones in the same vor.
  2. Full GC
    Organize the entire heap, including young, tenured, and perm. Full GC is slower than scavenge GC, so full GC should be minimized. Full GC may occur due to the following reasons:

    • Tenured full
    • Perm domain full
    • System. GC () is displayed and called
    • Dynamic change of heap domain allocation policies after the last GC

Demo of generation garbage collection process



Ii. Garbage Collector


Currently, there are three main collectors:Serial collector, parallel collector, and concurrent collector.

  1. Serial collector

    A single thread is used to process all garbage collection tasks. Because multi-thread interaction is not required, the efficiency is relatively high. However, the advantages of multi-processor cannot be used, so this collector is suitable for single-processor machines. Of course, this collector can also be used in small data volumes (100 m(Left and right) on a multi-processor machine. Available-XX: + useserialgcOpen.
  2. Parallel collector
    1. Parallel garbage collection for young generation can reduce the garbage collection time. Generally used on multi-threaded Multi-processor machines. Use-XX: + useparallelgc. Open. The parallel collector is introduced in the sixth update of j2se5.0 and is enhanced in Java se6.0-it can be used for parallel collection by heap elders.If the old generation does not use concurrent collection, it uses a single thread for garbage collection.Therefore, the scalability is restricted. Use-XX: + useparalleloldgcOpen.
    2. Use-XX: parallelgcthreads = <n>Sets the number of parallel garbage collection threads.This value can be set to be equal to the number of machine Processors.
    3. This collector can be configured as follows:
      • Maximum garbage collection pause:Specifies the maximum pause time for garbage collection.-XX: maxgcpausemillis = <n>. <N> millisecond. If this value is specified,The heap size and garbage collection parameters are adjusted to reach the specified value.. Setting this value may reduce the application throughput.
      • Throughput:Throughput isRatio of garbage collection time to non-garbage collection time, Through-XX: gctimeratio = <n>And the formula is1/(1 + n). For example, when-XX: gctimeratio = 19, it indicates that 5% of the time is used for garbage collection. The default value is 99, that is, 1% of the time is used for garbage collection.
  3. Concurrent collector
    It can ensure that most of the work is performed concurrently (the application does not stop), and garbage collection only suspends a small amount of time. This collector is suitable for medium and large scale applications with high response time requirements. Use-XX: + useconcmarksweepgcOpen.
    1. The concurrent collector mainly reduces the pause time of the old generation. It uses an independent garbage collection thread to track reachable objects without stopping the application. In each old generation garbage collection cycle, the concurrent collector will temporarily pause the entire application at the early stage of collection, and pause again during collection. The second pause will be a little longer than the first one. In this process, multiple threads perform garbage collection at the same time.
    2. Concurrent collector usageProcessor for a short pause. In a system with N processors, concurrent collection is usedK/nAvailable processors are recycled. Generally1 <= k <= N/4.
    3. OnlyConcurrent collectors are used on a processor host., SetIncremental ModeYou can also get a short pause time.
    4. Floating garbage: Because the application is running at the same time for garbage collection, some garbage may be generated when the garbage collection is completed, resulting in "floating garbage ", this garbage can be recycled only in the next garbage collection cycle. Therefore, concurrent collectors generally require20%The reserved space for these floating spam.
    5. Concurrent mode failure: The concurrent collector collects data when the application is running. Therefore, you must ensure that the heap has sufficient space for the program during the garbage collection period. Otherwise, garbage collection has not been completed, the heap space is full first. In this case, "concurrent mode failure" will occur, and the entire application will be paused for garbage collection.
    6. Start the concurrent collector: Because concurrent collection is collected during application running, you must ensure that there is sufficient memory space for the program to use before the collection is complete. Otherwise, "concurrent mode failure" appears ". Set-XX: cmsinitiatingoccupancyfraction = <n>Specify the number of remaining heaps to start concurrent collection
  4. Summary
    • Serial processor:
      -- Applicability: applications with a small data volume (about MB) and a single processor that have no requirements for response time.
      -- Disadvantage: it can only be used for small applications
    • Parallel processor:
      -- Applicability: medium and large applications with high throughput requirements, multiple CPUs, and no application response time requirements. Example: background processing and scientific computing.
      -- Disadvantage: The application response time may be long.
    • Concurrent processor:
      -- Applicability: medium and large applications with high requirements on response time, multiple CPUs, and high requirements on application response time. Example: Web server/application server, telecom exchange, and integrated development environment.

Iii. Common configuration examples

  1. Heap size settings
    The maximum heap size in JVM has three restrictions: the data model (32-BT or 64-bit) of the relevant operating system; the available virtual memory limit of the system; and the available physical memory limit of the system. Generally, 32-bit systems are limited to Gbps ~ 2 GB; 64 indicates that the operating system has unlimited memory. In Windows Server 2003, 1478 GB physical memory, and JDK, the maximum value is MB.
    Typical settings:

    • java -Xmx3550m -Xms3550m -Xmn2g -Xss128k
      -Xmx3550m: Set the maximum available JVM memory to 3550 MB.
      -Xms3550m: Set JVM to make the memory 3550 MB. This value can be set to the same as-xmx to avoid JVM re-allocating memory after each garbage collection.
      -Xmn2g: Set the young generation size to 2 GB.Total heap size = Young Generation size + Old Generation size + persistent generation size. The permanent generation usually has a fixed size of 64 M. Therefore, increasing the size of the young generation will reduce the size of the old generation. This value has a great impact on the system performance. Sun officially recommends 3/8 of the total heap configuration.
      -Xss128k: Set the stack size for each thread. After JDK 256, the size of each thread stack is 1 MB, and the size of each previous thread stack is K. The memory size required for more application threads is adjusted. Reduce this value to generate more threads in the same physical memory. However, the operating system still has a limit on the number of threads in a process. It cannot be generated infinitely. The experience is between 3000 and ~ About 5000.
    • java -Xmx3550m -Xms3550m -Xss128k -XX:NewRatio=4 -XX:SurvivorRatio=4 -XX:MaxPermSize=16m -XX:MaxTenuringThreshold=0
      -XX:NewRatio=4: Set the ratio of the young generation (including Eden and two primary vor regions) to the old generation (excluding the permanent generation ). If this parameter is set to 4, the ratio of the young generation to the old generation is, and the young generation accounts for 1/5 of the entire stack.
      -XX:SurvivorRatio=4: Set the ratio of Eden to vor in the young generation. If this parameter is set to 4, the ratio of two vor zones to One Eden zone is, and one vor zone accounts for 1/6 of the young generation.
      -XX:MaxPermSize=16m: Sets the persistent generation size to 16 Mb.
      -XX:MaxTenuringThreshold=0: Sets the maximum age of spam.If it is set to 0, the young generation object directly enters the old generation without going through the VOR area.. For applications with many older generations, the efficiency can be improved.If this value is set to a greater value, the young generation object will be copied multiple times in the same vor area, which can increase the survival time of the young generation object.To add an introduction to recycling in the young generation.
  2. Collector Selection
    JVM provides three options:Serial collector, parallel collector, and concurrent collectorBut the serial collector is only applicable to small data volumes. Therefore, the options here are mainly for parallel collectors and concurrent collectors. By default, jdk5.0 used a serial collector before. To use another collector, you must add the relevant parameters at startup. After jdk5.0, the JVM will judge based on the current system configuration.
    1. Throughput firstParallel collector
      As described above, parallel collectors are mainly aimed at reaching a certain throughput and are suitable for Science and Technology and background processing.
      Typical Configuration:

      • java -Xmx3800m -Xms3800m -Xmn2g -Xss128k -XX:+UseParallelGC -XX:ParallelGCThreads=20
        -XX:+UseParallelGC: Select the garbage collector as the parallel collector.This configuration is only valid for young generations. In the preceding configuration, the young generation uses concurrent collection, while the old generation uses serial collection.
        -XX:ParallelGCThreads=20: Configure the number of parallel collector threads, that is, the number of threads at the same time for garbage collection. It is best to set this value to be equal to the number of processors.
      • java -Xmx3550m -Xms3550m -Xmn2g -Xss128k -XX:+UseParallelGC -XX:ParallelGCThreads=20
        -XX:+UseParallelOldGC
        -XX:+UseParallelOldGC: Configure the garbage collection method for the old generation to parallel collection. Jdk6.0 supports parallel collection of older generations.
      • java -Xmx3550m -Xms3550m -Xmn2g -Xss128k -XX:+UseParallelGC -XX:MaxGCPauseMillis=100
        -XX:MaxGCPauseMillis=100:Sets the maximum time for garbage collection on the young generation. If this time cannot be met, the JVM automatically adjusts the size of the young generation to meet this value.
      • java -Xmx3550m -Xms3550m -Xmn2g -Xss128k -XX:+UseParallelGC -XX:MaxGCPauseMillis=100
        -XX: + useadaptivesizepolicy
        -XX: + useadaptivesizepolicy
        : After this option is set, the parallel collector automatically selects the young generation zone size and the corresponding proportion of the region vor zone to achieve the minimum corresponding time or collection frequency specified by the target system, we recommend that you enable the parallel collector all the time.
    2. Response time firstConcurrency collector
      As described above, the concurrent collector mainly ensures the system response time and reduces the pause time during garbage collection. Applicable to application servers and telecommunications fields.
      Typical Configuration:

      • java -Xmx3550m -Xms3550m -Xmn2g -Xss128k -XX:ParallelGCThreads=20
        -XX:+UseConcMarkSweepGC -XX:+UseParNewGC
        -XX:+UseConcMarkSweepGC: Set the age for concurrent collection. After this is configured in the test,-XX: the configuration of newratio = 4 is invalid for unknown reasons. Therefore, it is best to set the size of the young generation with-xmn.
        -XX:+UseParNewGC:Configure the young generation for parallel collection. It can be used together with CMS collection. Jdk5.0 or above, JVM will be set based on the system configuration, so you do not need to set this value.
      • java -Xmx3550m -Xms3550m -Xmn2g -Xss128k -XX:+UseConcMarkSweepGC
        -XX:CMSFullGCsBeforeCompaction=5 -XX: + usecmscompactatfullcollection
        -XX: cmsfullgcsbeforecompaction: Because the concurrent collector does not compress and organize the memory space, "fragments" are generated after running for a period of time, reducing the running efficiency. This value sets the number of GC operations to compress and organize the memory space.
        -XX: + usecmscompactatfullcollection: Enable compression for the old generation. Performance may be affected, but fragments can be eliminated.
  3. Auxiliary Information
    JVM provides a large number of command line parameters and prints information for debugging. There are mainly the following:
    • -XX: + printgc
      Output Format: [GC 118250 K-> 113543 K (130112 K), 0.0094143 secs]

      [Full GC 121376 K-> 10414 K (130112 K), 0.0650971 secs]

    • -XX: + printgcdetails
      Output Format: [GC [defnew: 8614 K-> 781 K (9088 K), 0.0123035 secs] 118250 K-> 113543 K (130112 K), 0.0124633 secs]

      [GC [defnew: 8614 K-> 8614 K (9088 K), 0.0000665 secs] [tenured: 112761 K-> 10414 K (121024 K ), 0.0433488 secs] 121376 K-> 10414 K (130112 K), 0.0436268 secs]

    • -XX: + printgctimestamps-XX: + printgc: printgctimestamps can be used together with the above two
      Output Format:11.851: [GC 98328 K-> 93620 K (130112 K), 0.0082960 secs]
    • -XX: + printgcapplicationconcurrenttime:Print the execution time of the program before each garbage collection. Can be used together with the above
      Output Format:Application Time: 0.5291524 seconds
    • -XX: + printgcapplicationstoppedtime: Print the time when the program is suspended during garbage collection. Can be used together with the above
      Output Format:Total time for which application threads were stopped: 0.0468229 seconds
    • -XX: + printheapatgc: Print detailed stack information before and after GC
      Output Format:
      34.702: [GC {heap before GC invocations = 7:
      Def New Generation total 55296 K, used 52568 K [0x1ebd0000, 0x227d0000, 0x227d0000)
      Eden space 49152 K, 99% used[0x1ebd0000, 0x21bce430, 0x21bd0000)
      From space 6144 K, 55% used[0x221d0000, 0x22527e10, 0x227d0000)
      To space 6144 K, 0% used [0x21bd0000, 0x21bd0000, 0x221d0000)
      Tenured generation total 69632 K, used 2696 K [0x227d0000, 0x26bd0000, 0x26bd0000)
      The space 69632 K, 3% used[0x227d0000, 0x22a720f8, 0x22a72200, 0x26bd0000)
      Compacting perm Gen total 8192 K, used 2898 K [0x26bd0000, 0x273d0000, 0x2abd0000)
      The space 8192 K, 35% used [0x26bd0000, 0x26ea4ba8, 0x26ea4c00, 0x273d0000)
      RO space 8192 K, 66% used [0x2abd0000, 0x2b12bcc0, 0x2b12be00, 0x2b3d0000)
      RW space 12288 K, 46% used [0x2b3d0000, 0x2b972060, 0x2b972200, 0x2bfd0000)
      34.735: [defnew: 52568 K-> 3433 K (55296 K), 0.0072126 secs] 55264 K-> 6615 K (124928 K)Heap after GC invocations = 8:
      Def New Generation total 55296 K, used 3433 K [0x1ebd0000, 0x227d0000, 0x227d0000)
      Eden space 49152 K, 0% used[0x1ebd0000, 0x1ebd0000, 0x21bd0000)
      From space 6144 K, 55% used [0x21bd0000, 0x21f2a5e8, 0x221d0000)
      To space 6144 K, 0% used [0x221d0000, 0x221d0000, 0x227d0000)
      Tenured generation total 69632 K, used 3182 K [0x227d0000, 0x26bd0000, 0x26bd0000)
      The space 69632 K, 4% used[0x227d0000, 0x22aeb958, 0x22aeba00, 0x26bd0000)
      Compacting perm Gen total 8192 K, used 2898 K [0x26bd0000, 0x273d0000, 0x2abd0000)
      The space 8192 K, 35% used [0x26bd0000, 0x26ea4ba8, 0x26ea4c00, 0x273d0000)
      RO space 8192 K, 66% used [0x2abd0000, 0x2b12bcc0, 0x2b12be00, 0x2b3d0000)
      RW space 12288 K, 46% used [0x2b3d0000, 0x2b972060, 0x2b972200, 0x2bfd0000)
      }
      , 0.0757599 secs]
    • -Xloggc: Filename: Used in combination with the above, the relevant log information is recorded in the file for analysis.
  4. Common configuration Summary
    1. Heap settings

      • -XMS: Initial heap size
      • -Xmx: Maximum heap size
      • -XX: newsize = N: Set the young generation size
      • -XX: newratio = N:Set the ratio of the young generation to the old generation. For example, if the value is 3, the ratio of the young generation to the old generation is. The young generation accounts for 1/4 of the young generation and the old generation.
      • -XX: Required vorratio = N: Ratio of the Eden region in the young generation to the two vor regions. Note that there are two vor zones. For example, 3 indicates EDEN: Primary vor =. One primary vor zone accounts for 1/5 of the young generation.
      • -XX: maxpermsize = N: Sets the persistent generation size.
    2. Collector settings
      • -XX: + useserialgc: Set the serial collector
      • -XX: + useparallelgc: Set parallel collectors
      • -XX: + useparalledloldgc: Set the parallel elder generation collector
      • -XX: + useconcmarksweepgc: Set concurrent collectors
    3. Garbage collection statistics
      • -XX: + printgc
      • -XX: + printgcdetails
      • -XX: + printgctimestamps
      • -Xloggc: Filename
    4. Parallel collector settings
      • -XX: parallelgcthreads = N: Set the number of CPUs used for parallel collector collection. Number of parallel collection threads.
      • -XX: maxgcpausemillis = N: Sets the maximum pause time for parallel collection.
      • -XX: gctimeratio = N: Set the percentage of the garbage collection time to the running time. The formula is 1/(1 + n)
    5. Concurrent collector settings
      • -XX: + cmsincrementalmode: Set to incremental mode. Applicable to a single CPU.
      • -XX: parallelgcthreads = N: Sets the number of CPUs used by the concurrent collector when the collection mode of the young generation is parallel collection. Number of parallel collection threads.

Iv. Optimization Summary

  1. Young Generation Size Selection

    • Response time-first applications:Set as large as possible until it is close to the minimum response time limit of the system(Select based on the actual situation ). In this case, the collection frequency of the young generation is also the smallest. At the same time, reduce the number of objects that reach the old generation.
    • Throughput-first applications: Set as large as possible, possibly to Gbit level. Because there is no requirement on the response time, garbage collection can be performed in parallel, which is generally suitable for applications with more than 8 CPUs.
  2. Old Generation Size Selection
    • Response time-first applications: The concurrency collector is used in the old generation, so the size must be carefully set.Concurrent session RateAndSession durationAnd other parameters. If the heap settings are small, it may cause memory fragmentation, high recovery frequency, and application suspension. The traditional mark clearing method is used. If the heap is large, it takes a long time to collect. For the optimal solution, you generally need to obtain the following data:

      • Concurrent garbage collection information
      • Number of persistent generation concurrent collection times
      • Traditional GC Information
      • Ratio of time spent on the recovery of young and old generations

      Reducing the time spent by the young and old generations will generally improve application efficiency.

    • Throughput-first applications: Generally, applications with high throughput have a large young generation and a small old generation. The reason is that most of the short-term objects can be recycled as much as possible to reduce the medium-term objects, while the old generation will store the long-term surviving objects as much as possible.
  3. Fragmentation problem caused by a small heap
    The heap is not compressed because the concurrent collector of the old generation uses the marking and clearing algorithms. When the collector recycles the object, it merges the adjacent space and assigns it to a large object. However, when the heap space is small and runs for a period of time, "fragments" will appear. If the concurrent collector cannot find enough space, the concurrent collector will stop, then, use the traditional marking and clearing methods for recycling. If "fragments" appear, you may need to configure the following:
    • -XX: + usecmscompactatfullcollection: Enable compression for the old generation when concurrent collectors are used.
    • -XX: cmsfullgcsbeforecompaction = 0: When the above configuration is enabled, how many full GC times are set here to compress the old generation?

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.