Java garbage collection mechanism concepts

Source: Internet
Author: User
Tags example of manual

Java garbage collection mechanism concepts

 

This article is an example of the Garbage Collection Handbook that will be published in a few weeks. At the same time, you can be familiar with the basic knowledge of garbage collection-this is chosen from the first chapter of the book.

At first glance, what garbage collection does should be exactly like its name-finding and clearing garbage. In fact, the opposite is true. Garbage collection tracks all objects that are still in use and marks the remaining objects as garbage. With this in mind, let's take a deeper look at how the automatic memory reclaim called "Garbage Collection" is implemented in JVM.

Manual Memory Management

Before introducing the modern version of garbage collection, let's briefly review the days when the memory needs to be manually explicitly allocated and released. If you forget to release the memory, the memory cannot be reused. This memory is occupied but not used. This scenario is calledMemory leakage.

The following is a simple example of manual memory management written in C:

int send_request() {    size_t n = read_size();    int *elements = malloc(n * sizeof(int));    if(read_elements(n, elements) < n) {        // elements not freed!        return -1;    }    // …    free(elements)    return 0;}

You can easily forget to release the memory. Memory leakage was a common problem. You can only fight against them by constantly fixing your own code. Therefore, a more elegant way is needed to automatically release useless memory to reduce the possibility of human error. This automated process is also called garbage collection (GC ).

Smart pointer

One early implementation of automatic garbage collection is reference counting. You know that each object has been referenced several times. When the counter is set to 0, this object can be safely recycled. The sharing pointer of C ++ is a very famous example:

int send_request() {    size_t n = read_size();    stared_ptr<vector<int>> elements               = make_shared<vector<int>&gt();    if(read_elements(n, elements) < n) {        return -1;    }    return 0;}

SharedPtr records the number of times this object is referenced. If you pass it to someone else, it will count and add one. When it leaves the scope, it will subtract one. Once this count is 0, sharedPtr automatically deletes the vector corresponding to the underlying layer. Of course this is just an example, because some readers have pointed out that this is unlikely to happen in reality, but it is sufficient for demonstration.

Automatic Memory Management

In the above C ++ code, We Have To explicitly declare that we need to use memory management. What if all objects adopt this mechanism? That is too convenient, so developers do not need to consider cleaning up the memory. The runtime will automatically know which memory is no longer used, and then release it. That is to say, it automatically recycles the garbage. The first generation of the garbage collector was introduced by Lisp in 1959, which has been evolving so far.

 

Reference count

 

The idea demonstrated by sharing pointers in C ++ can be applied to all objects. Many languages such as Perl, Python, and PHP use this method. This can be easily illustrated through a diagram:

 

The green cloud represents the objects that are still being used in the program. Technically, this is a bit like a local variable or a static variable in a method being executed. Different programming languages may be different, so this is not the focus of our attention.

The blue circle represents the objects in the memory. You can see how many objects reference them. No one has referenced the object in the gray circle. Therefore, they are spam objects and can be cleared by the garbage collector.

Looks pretty good, right? Yes, but there is a major defect here. It is easy to see some isolated loops. The objects in them are not in any domain, but they are referenced by each other, resulting in the number of references not 0. The following is an example:

As you can see, the red part is actually the garbage objects that are no longer used by the application. Memory leakage may occur due to reference counting defects.

There are several ways to solve this problem, such as using special "weak" references or using a special algorithm to recycle circular references. The previously mentioned Perl, Python, PHP, and other languages all use similar methods to recycle circular references, but this is beyond the scope of this article. We are going to introduce in detail the methods used by JVM.

Mark Deletion

First, the JVM should define the object accessibility. Unlike the previous definition of using a green cloud, Garbage Collection Roots has a very clear and specific Garbage Collection root object:

  • Local variable
  • Active thread
  • Static Field
  • JNI reference
  • Others will be discussed later)

JVM records all reachable objects by marking the deletion algorithm, and ensures that the memory of the inaccessible objects can be reused. This includes two steps:

  • A tag is used to traverse all reachable objects and record the object information in the local memory.
  • The deletion ensures that the memory address of the inaccessible object can be used in the next memory allocation.

Different GC algorithms in JVM, such as Parallel Scavenge, Parallel Mark + Copy, and CMS are different implementations of this algorithm, but they are only slightly different in each stage, in terms of concept, it still corresponds to the two steps mentioned above.

The most important thing about this implementation is that there will no longer be leakage of object loops:

The disadvantage is that the thread of the application needs to be paused before it can be recycled. If the reference remains changing, you cannot count it. This application is paused so that The JVM can clean up The housework, also known as Stop The World pause (STW ). There are many possibilities for triggering such a pause, but garbage collection should be the most common.

 

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.