Exploring Java garbage collection mechanism

Source: Internet
Author: User

GC (garbage collection) is one of the core technologies of Java. However, according to the internal running mechanism of JVM, Java's garbage collection principle and mechanism have not changed. The purpose of garbage collection is to clear objects that are no longer in use. GC determines whether to collect the object by determining whether the object is referenced by the active object. GC must first determine whether the object can be collected at the time. Two common methods are reference count and Object Reference traversal.

Reference counting collector

Reference count is an early policy in the garbage collector. In this method, each object (not referenced) in the heap has a reference count. When an object is created and assigned to a variable, the variable count is set to 1. When any other variable is assigned as a reference to this object, the count is incremented by 1 (
= B, then B references the object + 1), but when a reference of an object exceeds the lifecycle or is set to a new value, the reference count of the object is reduced by 1. Any object with 0 reference count can be collected as garbage. When an object is garbage collected, the number of objects it references is reduced by 1.

Advantage: The reference counting collector can be executed quickly and intertwined in the program running. It is advantageous to the real-time environment where the program is not interrupted for a long time.

Disadvantage: Circular references cannot be detected. If the parent object has a reference to the child object, the child object references the parent object in turn. In this way, their reference count will never be 0.

Tracking collector
 

Early JVMs used reference counting. Currently, most JVMs use Object Reference traversal. Object Reference traversal starts from a group of objects and recursively identifies reachable objects along each link in the entire object graph. If an object cannot be reached from one (at least one) of these root objects, it is collected as garbage. In the object traversal stage, GC must remember which objects can arrive in order to delete inaccessible objects. This is called a mark (marking) object.

Next, the GC will delete the inaccessible objects. During deletion, some GC simply scans the stack, deletes untagged objects, and releases their memory to generate new objects. This is called clearing ). The problem with this method is that the memory will be divided into many small segments, but they are not enough for new objects, but they are very large in combination. Therefore, many GC can reorganize the objects in the memory and compact them to form available space.

To this end, GC needs to stop other activities. This method means that all the work related to the application is stopped and only GC is run. As a result, many mixed requests are added or subtracted during the response. In addition, more complex GC increases or runs at the same time to reduce or clear application interruptions. Some GC uses a single thread to complete this task, while others use multiple threads to increase efficiency.

Some common garbage collectors

Clear collector

The collector first traverses the object graph and marks reachable objects, then scans the stack to find untagged objects and releases their memory. This type of collector generally uses a single thread to work and stops other operations. In addition, because it only clears unmarked objects and does not compress the marked objects, a large amount of memory fragments will be generated, thus wasting memory.

Compression collector

It is also called the Mark-clear-compression collector, which has the same mark stage as the Mark-clear collector. In the second stage, the tag object is copied to the new domain of the stack to compress the stack. This collector also stops other operations.

Copy collector

This collector divides the stack into two fields, which are often called semi-space. Only half of the space is used each time, and the new object generated by JVM is placed in the other half of the space. During GC running, it copies the reachable objects to the other half of the space, thus compressing the stack. This method is applicable to objects with a short lifetime, and objects with a long lifetime of continuous replication result in lower efficiency. In addition, the memory size of the specified size heap is doubled, because only half of the heap size is used at any time.

Incremental collector

The incremental collector divides the stack into multiple domains and collects garbage from only one domain at a time. It can also be understood as dividing the stack into a small block and collecting garbage from only one block at a time. This will cause a small amount of application interruption time, making it hard for users to notice that the garbage collector is working.

Generational collector

The disadvantage of the replication collector is that during each collection, all the marked objects will be copied. As a result, some objects with a long life cycle will be copied back and forth multiple times, which consumes a lot of time. The generational collector can solve this problem. the generational collector divides the stack into two or more fields to store objects of different lifetime. New objects generated by JVM are generally placed in a certain domain. After a period of time, the existing objects (non-short-lived objects) will get the validity period and be transferred to a domain with a longer life cycle. The generational collectors use different algorithms for different domains to optimize performance.

Parallel collector

The parallel collector uses a traditional algorithm and uses multiple threads to execute their work in parallel. Using multithreading on multiple CPU machines can significantly improve the scalability of Java applications.

Finally, a very simple example of tracking the Collector is provided to help you better understand the collector:

Legend of the trail collector

Notes for using the Garbage Collector

Here are some points to note about the garbage collector. The Garbage Collector has a lot of knowledge. Below we will only list some of the necessary knowledge:

◆ Each object can only call the finalize () method once. If an exception occurs during execution of the finalize () method, the object can still be collected by the garbage collector.

◆ The garbage collector tracks every object, collects untouchable objects (that is, the object is no longer referenced by the Program), and recycles the memory space occupied by the object. However, during garbage collection, the garbage collector calls the finalize () method of the object (if any ). If the finalize () method causes the object to be referenced by the Program (also known as "resurrected"), the object becomes a touchable object and will not be garbage collected for the moment. However, since each object can only call the finalize () method once, each object can only be "Revived" once.

◆ The Java language allows programmers to add the finalize () method to any method. This method will be called before the Garbage Collector exchanges and recycles objects. However, do not rely too much on this method to recycle and reuse system resources, because the execution result after this method is called is unpredictable.

◆ The Garbage Collector cannot be executed forcibly, but the programmer can investigate the system. GC method to recommend garbage collection. Remember, it's just a suggestion. Generally, it is not recommended to write system. GC by yourself, because it will increase the garbage collection workload.

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.