Java GC mechanism and Algorithm

Source: Internet
Author: User

Java GC mechanism and Algorithm
GC stage
For each object, garbage collection is divided into two stages: finalization and reclamation.

  • Finalization: the method used to run the finalize of this object.
  • Reclamation: reclaim the memory used by this object.
Basic steps of GC Process
  • First, make sure that the object is inaccessible and will be recycled soon.
  • Second, if the object has a finalize method, the object is added to the finalization queue, and the finalize method is called at a certain time point to release resources in finalize.
  • Finally, reclaim the memory occupied by the object.
Question about the finalize method
  • The finalize method enables the GC process to do more and increase the GC burden.
  • If the finalize method of an object runs too long, it will delay the execution of the finalize method of other objects.
  • If a strong reference is created in the finalize method to reference other objects, this will prevent this object from being GC.
  • The finalize method may be executed in an uncertain Order (that is, the finalize method should be avoided in scenarios with strict security requirements ).
  • It is not guaranteed that the finalize method will be called in time. Maybe the program has exited, but the finalize method has not yet been called.
Object Reference Type
  • Reference (or named Strong Reference): A normal Reference.
  • SoftReference: indicates the object to which this Reference points. If this object is not referenced by other Strong references, it may be GC at any time. GC may occur at any time, but it usually occurs before the program throws an OutOfMemoryError when the number of available memory is relatively low. SoftReference is usually used as an object reference to implement Cache. If this object is GC, it can be re-created at any time. In addition, according to the JDK documentation, the actual implementation of JVM encourages you Not to recycle recently created and recently used objects.
  • WeakReference: if an object referenced by WeakReference does not require any reference from SoftReference and StrongReference, it will be GC immediately. The difference between the WeakReference object and SoftReference is that the WeakReference object is called by eagerly collected, that is, once no SoftReference and StrongReference are referenced, It is clear immediately. However, only the objects referenced by SoftReference are unclear, it is cleared only when the memory is insufficient and an OutOfMemoryError occurs. SoftReference is suitable for Cache.
  • PhantomReference: GC is available at any time when StrongReference, SoftReference, and WeakReference are not referenced. Usually used together with ReferenceQueue to manage and clear local resources related to the referenced object (no finalize method.
GC Metrics)
  • Throughput (Throughput): the percentage of all times that are not spent on GC execution to the total running time.
  • Pauses: the number of times the program is paused when the GC is running. Or the average duration and maximum duration of the pause in the number of pauses you are interested in.
  • Footprint (Footprint ?) : The current heap memory size.
  • Promptness (timeliness): objects that are no longer in use can be cleared and their memory is released for a long time.
General GC Algorithm
All GC algorithms used by Java are variants of the general GC algorithm concept.
General GC algorithm assumptions:
  • Recently created objects may soon be inaccessible (unreachable, which can be recycled). For example, when the local variable declared inside the method is run out of the scope of the local variable, objects referenced by local variables will soon be inaccessible.
  • The longer an object is reachable, the more impossible it will be to be recycled.
In Java GC, objects are divided into generations (generation) or spaces (Space ). Java divides objects into young, tenured, and perm ). During GC, objects are moved from one space to another.
Object Spaces (Object Space)
  • Young: the Young generation retains the newly created objects. The objects in this generation can be "minor" or "major" collected and recycled.
  • Tenured: objects that survive in the young generation are stored in the old generation and can only be recycled in the major.
  • Perm: Permanently saves JVM objects, such as Class objects and Method objects, as well as their bytecode and internal strings. GC of objects in Perm means that all classes are detached.
The size of each space is determined by the current memory size and can be changed at runtime. Shows the relationship between each space:


Young Spaces (Young space)
  • Eden space: stores newly created objects since the last GC, except Perm objects. When the minor collection occurs, the objects or GC in the Eden space are cleared, or moved to the same vor space.
  • Stored vor spaces: This space stores young objects that have survived the last GC. In minor GC, these objects can be cleared by GC, or moved to another volume vor space.
Minor collections and Major collections
  • Minor collection is executed when the young space is full. It is faster than major collections, because minor collection only checks a subset object corresponding to the major collection. Minor collection occurs more frequently than major collection.
  • The Major collection is executed when the tenured space is full. It clears tenured and young.
Three methods of GC operation
There are 4 garbage collection algorithms in Java 5 and Java 6, and one of them will not be supported. The three remaining garbage collection algorithms are: Serial,ThroughputandConcurrent low pause.
  • Stop the world (Stop all programs): GC running in this mode is not allowed to run all programs in the JVM before GC is completed. Serial collector collects minor and major at this time. Throughput collector at this time as major collector.
  • Incremental (Incremental running mode): currently, Java GC algorithm is not required to support this running mode. When GC is run in this way, GC allows the program to do a short period of work and then perform garbage collection.
  • Concurrent (run in parallel): Throughput collector performs minor collect at this time. Concurrent low pause collector collects minor and major at this time. In this mode, the GC and program run in parallel, so the program is temporarily suspended.
GC Algorithm
  • Serial Algorithm: Use-XX: + UseSerialGC to enable GC for this algorithm. GC uses the same thread as the application for minor collection and major collection.
  • Throughput: Use-XX: + UseParallelGC to enable this algorithm GC. GC uses multiple threads for minor collection to reduce the program stop time. However, for the major collection, it is still done using the same thread as the program. When a program has a multi-core cpu and a large number of short-lived objects, it is better to have no restrictions on the program pause time.
  • Concurrent Low Pause: Enable this algorithm GC with-XX: + UseConcMarkSweepGC. Use multiple threads for minor and major collection. It works better when there are multi-core CPUs and a large number of objects with a long life cycle, and there are restrictions on the program pause time.
When does GC occur?
GC is affected by the heap memory size. If the heap memory is small, GC will be executed quickly, but will be quickly filled up, So GC is more frequent. If the heap memory is large, GC will be executed slowly, and will not be quickly filled up, so the execution frequency is relatively low.

Basic GC debugging
Throughput goal-XX: GCTimeRatio = n: indicates the total CPU time consumed to run the program.
Maximum pause time goal-XX: MaxGCPauseMillis = n: maximum number of milliseconds the program is paused for each GC.
Footprint goal: if other targets are reached, the heap size is reduced first until the first two goals are no longer satisfied and then increase slowly. Until the first two goal s are met.
-Xms = n (starting) and-Xmx = n (maximum) heap size. These two parameters should be familiar with, namely, the minimum heap memory used by JVM and the maximum heap memory.
-XX: MinHeapFreeRatio = n,-XX: MaxHeapFreeRatio = n: Minimum and maximum ratio of idle heap memory to used heap memory. When the percentage of idle heap memory is less than MinHeapFreeRatio, the memory space starts to expand. When the percentage of idle heap memory exceeds MaxHeapFreeRatio, the memory space starts to decrease.
-XX: NewSize = n,-XX: MaxNewSize = n: Default young space size (including eden + elastic vor 1 + elastic vor 2 ).
-XX: NewRatio = n: Ratio of young to tenured.
-XX: proportion vorratio = n: Ratio between each region vor space and eden.
-XX: MaxPermSize = n: maximum size of perm.
-XX: target1_vorratio = n: Target proportion of the surviving space after each GC.
-XX: + DisableExplicitGC: When this parameter is enabled, calling System. gc () in the program will not work. The default value is off.
-XX: + ScavengeBeforeFullGC: When this parameter is enabled, minor collection is executed every time the major collection is enabled. Enabled by default.
-XX: + UseGCOverheadLimit: When this parameter is enabled, If GC is performed for 98% of the total running time, an OutOfMemmoryError is thrown. Enabled by default.

References: http://java.ociweb.com/mark/other-presentations/JavaGC.pdf

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.