Garbage collection mechanism in Java

Source: Internet
Author: User

What is garbage?

In Java, it is associated with an object by reference, that is, if you want to manipulate the object, you must do so by reference.

An object that loses a referential relationship, called a garbage object.

Garbage collection algorithm

1. Reference counting method

According to the definition of "garbage", the intuitive approach is to set a reference counter for each object. When you scan an object, it is considered garbage if its reference is 0, and you are ready to recycle.

However, the disadvantage of this is that there is no way to eliminate garbage objects that are circular references, such as:

public class Main {public static void main (string[] args) {MyObject object1 = new MyObject ();                 MyObject object2 = new MyObject ();        Object1.object = Object2;                 Object2.object = Object1;        Object1 = null;    Object2 = null; }} class myobject{public object object = NULL;}

Although the references to Object1 and Object2 are eliminated, the reference count is not 0 because they still point to each other, so they are not recycled. In order to solve this problem, there is a second approach, the accessibility analysis method.

2. Accessibility Analysis method

The basic idea of this method is to search by a series of "GC Roots" objects as a starting point, if there is no unreachable path between "GC Roots" and an object, it is said that the object is unreachable, but it is important to note that objects that are judged to be unreachable do not necessarily become recyclable objects. An object that is judged unreachable must undergo at least two marking processes to become a recoverable object, and if it is still not possible to escape from being a recyclable object during these two marks, it is essentially a recyclable object.

Garbage collection mechanism in Java

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: 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.